diff --git a/.devops/cann.Dockerfile b/.devops/cann.Dockerfile index 182c71cdf172..83df409506fd 100644 --- a/.devops/cann.Dockerfile +++ b/.devops/cann.Dockerfile @@ -19,12 +19,15 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI from its source 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/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${CANN_BASE_IMAGE} AS build @@ -40,7 +43,7 @@ WORKDIR /app # -- Copy project files -- COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist # -- Set CANN environment variables (required for compilation) -- # Using ENV instead of `source` allows environment variables to persist across the entire image layer diff --git a/.devops/cpu.Dockerfile b/.devops/cpu.Dockerfile index 0809c8b7ec90..e195b5ac8b53 100644 --- a/.devops/cpu.Dockerfile +++ b/.devops/cpu.Dockerfile @@ -9,12 +9,15 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI from its source 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/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build @@ -28,7 +31,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN if [ "$TARGETARCH" = "amd64" ] || [ "$TARGETARCH" = "arm64" ]; then \ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DGGML_NATIVE=OFF -DLLAMA_BUILD_TESTS=OFF -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON; \ diff --git a/.devops/cuda.Dockerfile b/.devops/cuda.Dockerfile index 2c872ab4adeb..20501c1beac2 100644 --- a/.devops/cuda.Dockerfile +++ b/.devops/cuda.Dockerfile @@ -17,12 +17,15 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI from its source 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/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${BASE_CUDA_DEV_CONTAINER} AS build @@ -40,7 +43,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN if [ "${CUDA_DOCKER_ARCH}" != "default" ]; then \ export CMAKE_ARGS="-DCMAKE_CUDA_ARCHITECTURES=${CUDA_DOCKER_ARCH}"; \ diff --git a/.devops/intel.Dockerfile b/.devops/intel.Dockerfile index 9f4a8fc992e5..16326ebbdea5 100644 --- a/.devops/intel.Dockerfile +++ b/.devops/intel.Dockerfile @@ -11,12 +11,15 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI from its source 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/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/intel/deep-learning-essentials:$ONEAPI_VERSION AS build @@ -41,7 +44,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN if [ "${GGML_SYCL_F16}" = "ON" ]; then \ echo "GGML_SYCL_F16 is set" \ diff --git a/.devops/musa.Dockerfile b/.devops/musa.Dockerfile index 84969675a2df..dbf9e0b41122 100644 --- a/.devops/musa.Dockerfile +++ b/.devops/musa.Dockerfile @@ -15,12 +15,15 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI from its source 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/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${BASE_MUSA_DEV_CONTAINER} AS build @@ -45,7 +48,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN if [ "${MUSA_DOCKER_ARCH}" != "default" ]; then \ export CMAKE_ARGS="-DMUSA_ARCHITECTURES=${MUSA_DOCKER_ARCH}"; \ diff --git a/.devops/nix/package.nix b/.devops/nix/package.nix index e807b4d711eb..4ac844ff959d 100644 --- a/.devops/nix/package.nix +++ b/.devops/nix/package.nix @@ -22,12 +22,19 @@ spirv-headers, nodejs, importNpmLock, + syclToolkit ? null, + level-zero, + ocl-icd, + intel-graphics-compiler, + intel-compute-runtime, + makeBinaryWrapper, useBlas ? builtins.all (x: !x) [ useCuda useMetalKit useRocm useVulkan + useSycl ] && blas.meta.available, useCuda ? config.cudaSupport, @@ -38,11 +45,28 @@ rocmGpuTargets ? builtins.concatStringsSep ";" rocmPackages.clr.gpuTargets, useVulkan ? false, useRpc ? false, + useSycl ? false, + # Rebuild, not a runtime switch. cmake default is off. + syclF16 ? false, + # null keeps JIT. AOT makes icpx run ocloc, which DPC++ does not ship. + syclDeviceArch ? null, + syclMaxParallelLinkJobs ? null, llamaVersion ? "0.0.0", # Arbitrary version, substituted by the flake - # It's necessary to consistently use backendStdenv when building with CUDA support, - # otherwise we get libstdc++ errors downstream. - effectiveStdenv ? if useCuda then cudaPackages.backendStdenv else stdenv, + # CUDA needs its backend stdenv or libstdc++ mismatches downstream. + # SYCL needs icpx which is provided by the oneAPI stdenv + effectiveStdenv ? + if useCuda && useSycl then + throw "llama-cpp: useCuda and useSycl are mutually exclusive" + else if useCuda then + cudaPackages.backendStdenv + else if useSycl then + if syclToolkit == null then + throw "llama-cpp: useSycl requires syclToolkit, consider setting it to intel-oneapi-toolkit" + else + syclToolkit.stdenv + else + stdenv, enableStatic ? effectiveStdenv.hostPlatform.isStatic, precompileMetalShaders ? false, useWebUi ? true, @@ -65,7 +89,8 @@ let ++ lib.optionals useMetalKit [ "MetalKit" ] ++ lib.optionals useMpi [ "MPI" ] ++ lib.optionals useRocm [ "ROCm" ] - ++ lib.optionals useVulkan [ "Vulkan" ]; + ++ lib.optionals useVulkan [ "Vulkan" ] + ++ lib.optionals useSycl [ "SYCL" ]; pnameSuffix = strings.optionalString (suffices != [ ]) @@ -108,6 +133,26 @@ let shaderc spirv-headers ]; + + syclAot = useSycl && syclDeviceArch != null && syclDeviceArch != ""; + + # source ocloc binary from intel-compute-runtime + oclocAot = runCommand "ocloc-aot" { nativeBuildInputs = [ makeBinaryWrapper ]; } '' + mkdir -p "$out/bin" + shopt -s nullglob + exact=(${lib.getBin intel-compute-runtime}/bin/ocloc) + vers=(${lib.getBin intel-compute-runtime}/bin/ocloc-*) + if [ ''${#exact[@]} -eq 1 ]; then + src=''${exact[0]} + elif [ ''${#vers[@]} -eq 1 ]; then + src=''${vers[0]} + else + echo "expected one ocloc binary from intel-compute-runtime" >&2 + exit 1 + fi + makeWrapper "$src" "$out/bin/ocloc" \ + --prefix LD_LIBRARY_PATH : ${lib.makeLibraryPath [ intel-graphics-compiler ]} + ''; in effectiveStdenv.mkDerivation (finalAttrs: { @@ -133,11 +178,13 @@ effectiveStdenv.mkDerivation (finalAttrs: { src = lib.cleanSource ../../.; }; - # Builds the webui locally, taking care not to require updating any sha256 hash. + # Builds Llama Chat locally, taking care not to require updating any sha256 hash. webui = stdenvNoCC.mkDerivation { pname = "webui"; version = llamaVersion; - src = lib.cleanSource ../../tools/ui; + # the app compiles Llama UI from its source in ../../lib/ui, so the source is ui/ as a whole + src = lib.cleanSource ../../ui; + sourceRoot = "source/apps/chat"; nativeBuildInputs = [ nodejs @@ -146,7 +193,7 @@ effectiveStdenv.mkDerivation (finalAttrs: { # no sha256 required when using buildNodeModules npmDeps = importNpmLock.buildNodeModules { - npmRoot = ../../tools/ui; + npmRoot = ../../ui/apps/chat; inherit nodejs; }; @@ -156,8 +203,8 @@ effectiveStdenv.mkDerivation (finalAttrs: { }; postPatch = lib.optionalString useWebUi '' - cp -r ${finalAttrs.webui} tools/ui/dist - chmod -R u+w tools/ui/dist + cp -r ${finalAttrs.webui} ui/apps/chat/dist + chmod -R u+w ui/apps/chat/dist ''; # With PR#6015 https://github.com/ggml-org/llama.cpp/pull/6015, @@ -168,6 +215,13 @@ effectiveStdenv.mkDerivation (finalAttrs: { # see https://github.com/ggml-org/llama.cpp/pull/6118 for discussion __noChroot = effectiveStdenv.hostPlatform.isDarwin && useMetalKit && precompileMetalShaders; + # Do not fortify under SYCL as it breaks compiled memcpy invocations + # _FORTIFY_SOURCE rewrites memcpy -> __memcpy_chk + hardeningDisable = optionals useSycl [ + "fortify" + "fortify3" + ]; + nativeBuildInputs = [ cmake @@ -181,7 +235,12 @@ effectiveStdenv.mkDerivation (finalAttrs: { autoAddDriverRunpath ] ++ optionals (effectiveStdenv.hostPlatform.isGnu && enableStatic) [ glibc.static ] - ++ optionals (effectiveStdenv.hostPlatform.isDarwin && useMetalKit && precompileMetalShaders) [ xcrunHost ]; + ++ optionals (effectiveStdenv.hostPlatform.isDarwin && useMetalKit && precompileMetalShaders) [ xcrunHost ] + ++ optionals useSycl [ + autoAddDriverRunpath + makeBinaryWrapper + ] + ++ optionals syclAot [ oclocAot ]; buildInputs = optionals effectiveStdenv.hostPlatform.isDarwin darwinBuildInputs @@ -190,39 +249,53 @@ effectiveStdenv.mkDerivation (finalAttrs: { ++ optionals useRocm rocmBuildInputs ++ optionals useBlas [ blas ] ++ optionals useVulkan vulkanBuildInputs + ++ optionals useSycl [ + level-zero + ocl-icd + intel-graphics-compiler + ] ++ [ openssl ]; - cmakeFlags = - [ - (cmakeBool "LLAMA_BUILD_SERVER" true) - (cmakeBool "LLAMA_BUILD_WEBUI" useWebUi) - (cmakeBool "BUILD_SHARED_LIBS" (!enableStatic)) - (cmakeBool "CMAKE_SKIP_BUILD_RPATH" true) - (cmakeBool "GGML_NATIVE" false) - (cmakeBool "GGML_BLAS" useBlas) - (cmakeBool "GGML_CUDA" useCuda) - (cmakeBool "GGML_HIP" useRocm) - (cmakeBool "GGML_METAL" useMetalKit) - (cmakeBool "GGML_VULKAN" useVulkan) - (cmakeBool "GGML_STATIC" enableStatic) - (cmakeBool "GGML_RPC" useRpc) - ] - ++ optionals useCuda [ - ( - with cudaPackages.flags; - cmakeFeature "CMAKE_CUDA_ARCHITECTURES" ( - builtins.concatStringsSep ";" (map dropDot cudaCapabilities) - ) + cmakeFlags = [ + (cmakeBool "LLAMA_BUILD_SERVER" true) + (cmakeBool "LLAMA_BUILD_WEBUI" useWebUi) + (cmakeBool "BUILD_SHARED_LIBS" (!enableStatic)) + (cmakeBool "CMAKE_SKIP_BUILD_RPATH" true) + (cmakeBool "GGML_NATIVE" false) + (cmakeBool "GGML_BLAS" useBlas) + (cmakeBool "GGML_CUDA" useCuda) + (cmakeBool "GGML_HIP" useRocm) + (cmakeBool "GGML_METAL" useMetalKit) + (cmakeBool "GGML_VULKAN" useVulkan) + (cmakeBool "GGML_STATIC" enableStatic) + (cmakeBool "GGML_RPC" useRpc) + ] + ++ optionals useCuda [ + ( + with cudaPackages.flags; + cmakeFeature "CMAKE_CUDA_ARCHITECTURES" ( + builtins.concatStringsSep ";" (map dropDot cudaCapabilities) ) - ] - ++ optionals useRocm [ - (cmakeFeature "CMAKE_HIP_COMPILER" "${rocmPackages.llvm.clang}/bin/clang") - (cmakeFeature "CMAKE_HIP_ARCHITECTURES" rocmGpuTargets) - ] - ++ optionals useMetalKit [ - (lib.cmakeFeature "CMAKE_C_FLAGS" "-D__ARM_FEATURE_DOTPROD=1") - (cmakeBool "GGML_METAL_EMBED_LIBRARY" (!precompileMetalShaders)) - ]; + ) + ] + ++ optionals useRocm [ + (cmakeFeature "CMAKE_HIP_COMPILER" "${rocmPackages.llvm.clang}/bin/clang") + (cmakeFeature "CMAKE_HIP_ARCHITECTURES" rocmGpuTargets) + ] + ++ optionals useMetalKit [ + (lib.cmakeFeature "CMAKE_C_FLAGS" "-D__ARM_FEATURE_DOTPROD=1") + (cmakeBool "GGML_METAL_EMBED_LIBRARY" (!precompileMetalShaders)) + ] + ++ optionals useSycl [ + (cmakeBool "GGML_SYCL" true) + (cmakeBool "GGML_SYCL_F16" syclF16) + ] + ++ optionals syclAot [ + (cmakeFeature "GGML_SYCL_DEVICE_ARCH" syclDeviceArch) + ] + ++ optionals (syclAot && syclMaxParallelLinkJobs != null) [ + (cmakeFeature "GGML_SYCL_MAX_PARALLEL_LINK_JOBS" (toString syclMaxParallelLinkJobs)) + ]; # Environment variables needed for ROCm env = optionalAttrs useRocm { @@ -237,11 +310,35 @@ effectiveStdenv.mkDerivation (finalAttrs: { cp $src/include/llama.h $out/include/ ''; + # Fix SYCL binary calling missing important libraries + # Also use Level Zero + sysman INSTEAD of OpenCL + # due to OpenCL reporting free memory as total memory, + # breaking `-fit` functionality + postFixup = lib.optionalString useSycl '' + driverLibs=${ + lib.makeLibraryPath [ + intel-graphics-compiler + ocl-icd + ] + } + for b in "$out"/bin/*; do + [ -f "$b" ] && [ -x "$b" ] || continue + patchelf --print-interpreter "$b" >/dev/null 2>&1 || continue + patchelf --add-needed libOpenCL.so.1 --add-needed libigc.so.2 \ + --add-rpath "$driverLibs" "$b" + wrapProgram "$b" \ + --set-default ONEAPI_DEVICE_SELECTOR level_zero:gpu \ + --set-default ZES_ENABLE_SYSMAN 1 + done + ''; + meta = { # Configurations we don't want even the CI to evaluate. Results in the # "unsupported platform" messages. This is mostly a no-op, because # cudaPackages would've refused to evaluate anyway. - badPlatforms = optionals useCuda lib.platforms.darwin; + badPlatforms = + optionals useCuda lib.platforms.darwin + ++ optionals useSycl (lib.subtractLists [ "x86_64-linux" ] lib.platforms.all); # Configurations that are known to result in build failures. Can be # overridden by importing Nixpkgs with `allowBroken = true`. diff --git a/.devops/openvino.Dockerfile b/.devops/openvino.Dockerfile index 680ad7db6968..c88cc2bbb5f9 100644 --- a/.devops/openvino.Dockerfile +++ b/.devops/openvino.Dockerfile @@ -3,11 +3,11 @@ ARG OPENVINO_VERSION_FULL=2026.4.1.22982.07f9c262b05 ARG UBUNTU_VERSION=24.04 # Intel GPU driver versions. https://github.com/intel/compute-runtime/releases -ARG IGC_VERSION=v2.41.5 -ARG IGC_VERSION_FULL=2_2.41.5+22716 -ARG COMPUTE_RUNTIME_VERSION=26.35.39758.10 -ARG COMPUTE_RUNTIME_VERSION_FULL=26.35.39758.10-0 -ARG IGDGMM_VERSION=22.10.0 +ARG IGC_VERSION=v2.42.6 +ARG IGC_VERSION_FULL=2_2.42.6+23070 +ARG COMPUTE_RUNTIME_VERSION=26.40.40196.8 +ARG COMPUTE_RUNTIME_VERSION_FULL=26.40.40196.8-0 +ARG IGDGMM_VERSION=22.10.2 # Intel NPU driver versions. https://github.com/intel/linux-npu-driver/releases ARG NPU_DRIVER_VERSION=v1.38.0 @@ -28,12 +28,15 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI from its source 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/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build ## Build Image @@ -83,7 +86,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist # Build Stage RUN bash -c "source ${OpenVINO_DIR}/setupvars.sh && \ diff --git a/.devops/rocm.Dockerfile b/.devops/rocm.Dockerfile index 310f4f6d9485..9e667660f00e 100644 --- a/.devops/rocm.Dockerfile +++ b/.devops/rocm.Dockerfile @@ -17,12 +17,15 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI from its source 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/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build ### Build image @@ -52,7 +55,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN HIPCXX="$(hipconfig -l)/clang" HIP_PATH="$(hipconfig -R)" \ cmake -S . -B build \ diff --git a/.devops/vulkan.Dockerfile b/.devops/vulkan.Dockerfile index 96b7e66ec0e0..dc8a87667205 100644 --- a/.devops/vulkan.Dockerfile +++ b/.devops/vulkan.Dockerfile @@ -9,12 +9,15 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI from its source 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/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build @@ -31,7 +34,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN cmake -B build -DGGML_NATIVE=OFF -DGGML_VULKAN=ON -DLLAMA_BUILD_TESTS=OFF -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON && \ cmake --build build --config Release -j$(nproc) diff --git a/.devops/zendnn.Dockerfile b/.devops/zendnn.Dockerfile index a6e54ca8511f..cbc3696ed643 100644 --- a/.devops/zendnn.Dockerfile +++ b/.devops/zendnn.Dockerfile @@ -9,12 +9,15 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI from its source 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/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build @@ -28,7 +31,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DGGML_NATIVE=OFF -DLLAMA_BUILD_TESTS=OFF -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON -DGGML_ZENDNN=ON && \ cmake --build build -j $(nproc) diff --git a/.dockerignore b/.dockerignore index 0b81e83bf5d4..083eaed9c459 100644 --- a/.dockerignore +++ b/.dockerignore @@ -10,7 +10,7 @@ build*/ -tools/ui/node_modules/ +ui/apps/chat/node_modules/ models/* diff --git a/.editorconfig b/.editorconfig index 1474554f8ab7..5272e6ce0985 100644 --- a/.editorconfig +++ b/.editorconfig @@ -48,7 +48,7 @@ insert_final_newline = unset [vendor/**.patch] trim_trailing_whitespace = unset -[tools/ui/**] +[ui/**] indent_style = unset indent_size = unset end_of_line = unset diff --git a/.github/actions/get-tag-name/action.yml b/.github/actions/get-tag-name/action.yml index 46acce5828e9..ad50f8cfc390 100644 --- a/.github/actions/get-tag-name/action.yml +++ b/.github/actions/get-tag-name/action.yml @@ -14,7 +14,9 @@ runs: run: | BUILD_NUMBER="$(git rev-list --count HEAD)" SHORT_HASH="$(git rev-parse --short=7 HEAD)" - if [[ "${{ env.BRANCH_NAME }}" == "master" || "${{ env.BRANCH_NAME }}" == "b${BUILD_NUMBER}" ]]; then + if [[ "$GITHUB_REF_TYPE" == "tag" && "${{ env.BRANCH_NAME }}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "name=${{ env.BRANCH_NAME }}" >> $GITHUB_OUTPUT + elif [[ "${{ env.BRANCH_NAME }}" == "master" || "${{ env.BRANCH_NAME }}" == "b${BUILD_NUMBER}" ]]; then echo "name=b${BUILD_NUMBER}" >> $GITHUB_OUTPUT else SAFE_NAME=$(echo "${{ env.BRANCH_NAME }}" | tr '/' '-') diff --git a/.github/actions/windows-setup-cuda/action.yml b/.github/actions/windows-setup-cuda/action.yml index 51f1147e18b8..7548719bc7a5 100644 --- a/.github/actions/windows-setup-cuda/action.yml +++ b/.github/actions/windows-setup-cuda/action.yml @@ -25,7 +25,9 @@ runs: curl -O "https://developer.download.nvidia.com/compute/cuda/redist/visual_studio_integration/windows-x86_64/visual_studio_integration-windows-x86_64-11.7.91-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvprof/windows-x86_64/cuda_nvprof-windows-x86_64-11.7.101-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_cccl/windows-x86_64/cuda_cccl-windows-x86_64-11.7.91-archive.zip" + curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvml_dev/windows-x86_64/cuda_nvml_dev-windows-x86_64-11.7.91-archive.zip" unzip '*.zip' -d "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7" + xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7\cuda_nvml_dev-windows-x86_64-11.7.91-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7\cuda_cudart-windows-x86_64-11.7.99-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7\cuda_nvcc-windows-x86_64-11.7.99-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7\cuda_nvrtc-windows-x86_64-11.7.99-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7" /E /I /H /Y @@ -54,7 +56,9 @@ runs: curl -O "https://developer.download.nvidia.com/compute/cuda/redist/visual_studio_integration/windows-x86_64/visual_studio_integration-windows-x86_64-12.4.127-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvprof/windows-x86_64/cuda_nvprof-windows-x86_64-12.4.127-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_cccl/windows-x86_64/cuda_cccl-windows-x86_64-12.4.127-archive.zip" + curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvml_dev/windows-x86_64/cuda_nvml_dev-windows-x86_64-12.4.127-archive.zip" unzip '*.zip' -d "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4" + xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4\cuda_nvml_dev-windows-x86_64-12.4.127-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4\cuda_cudart-windows-x86_64-12.4.127-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4\cuda_nvcc-windows-x86_64-12.4.131-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4\cuda_nvrtc-windows-x86_64-12.4.127-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4" /E /I /H /Y @@ -85,7 +89,9 @@ runs: curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_profiler_api/windows-x86_64/cuda_profiler_api-windows-x86_64-13.1.80-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/visual_studio_integration/windows-x86_64/visual_studio_integration-windows-x86_64-13.1.68-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_cccl/windows-x86_64/cuda_cccl-windows-x86_64-13.1.78-archive.zip" + curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvml_dev/windows-x86_64/cuda_nvml_dev-windows-x86_64-13.1.68-archive.zip" unzip '*.zip' -d "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1" + xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1\cuda_nvml_dev-windows-x86_64-13.1.68-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1\cuda_crt-windows-x86_64-13.1.80-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1\cuda_cudart-windows-x86_64-13.1.80-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1\cuda_nvcc-windows-x86_64-13.1.80-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1" /E /I /H /Y @@ -116,7 +122,9 @@ runs: curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_profiler_api/windows-x86_64/cuda_profiler_api-windows-x86_64-13.5.25-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/visual_studio_integration/windows-x86_64/visual_studio_integration-windows-x86_64-13.5.25-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cccl/windows-x86_64/cccl-windows-x86_64-13.3.5.0.6-archive.zip" + curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvml_dev/windows-x86_64/cuda_nvml_dev-windows-x86_64-13.5.37-archive.zip" unzip '*.zip' -d "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" + xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_nvml_dev-windows-x86_64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_crt-windows-x86_64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_cudart-windows-x86_64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_nvcc-windows-x86_64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y @@ -143,7 +151,9 @@ runs: curl -O "https://developer.download.nvidia.com/compute/cuda/redist/libnvvm/windows-x86_64/libnvvm-windows-x86_64-13.5.37-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_cudart/windows-arm64/cuda_cudart-windows-arm64-13.5.37-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/libcublas/windows-arm64/libcublas-windows-arm64-13.10.0.20-archive.zip" + curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvml_dev/windows-arm64/cuda_nvml_dev-windows-arm64-13.5.37-archive.zip" unzip '*.zip' -d "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" + xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_nvml_dev-windows-arm64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cccl-windows-x86_64-13.3.5.0.6-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_crt-windows-x86_64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_nvcc-windows-x86_64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y diff --git a/.github/labeler.yml b/.github/labeler.yml index 20e19c35234e..6b1b0046762d 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -48,7 +48,6 @@ examples: - all-globs-to-all-files: - '!tools/server/**' - '!tools/mtmd/**' - - '!tools/ui/**' testing: - changed-files: - any-glob-to-any-file: @@ -72,7 +71,7 @@ android: server/ui: - changed-files: - any-glob-to-any-file: - - tools/ui/** + - ui/** server: - changed-files: - any-glob-to-any-file: diff --git a/.github/workflows/behavior-check.yml b/.github/workflows/behavior-check.yml index 73c3b8fe223a..544fb6caf600 100644 --- a/.github/workflows/behavior-check.yml +++ b/.github/workflows/behavior-check.yml @@ -140,6 +140,11 @@ jobs: source .venv/Scripts/activate pip install -r requirements/requirements-convert_hf_to_gguf.txt + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Build id: cmake_build shell: cmd diff --git a/.github/workflows/build-cpu.yml b/.github/workflows/build-cpu.yml index 35d610e1e9fc..285a01a7c860 100644 --- a/.github/workflows/build-cpu.yml +++ b/.github/workflows/build-cpu.yml @@ -187,6 +187,11 @@ jobs: run: | choco install ninja + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Build id: cmake_build run: | diff --git a/.github/workflows/build-cuda-ubuntu.yml b/.github/workflows/build-cuda-ubuntu.yml index db97aeb15b29..cdbbb4767332 100644 --- a/.github/workflows/build-cuda-ubuntu.yml +++ b/.github/workflows/build-cuda-ubuntu.yml @@ -98,7 +98,7 @@ jobs: hip: runs-on: ubuntu-22.04 - container: rocm/dev-ubuntu-22.04:6.1.2 + container: rocm/dev-ubuntu-22.04:6.3.4 steps: - name: Clone diff --git a/.github/workflows/build-opencl.yml b/.github/workflows/build-opencl.yml index ab9ed3ec2cb6..4b45ae666b4e 100644 --- a/.github/workflows/build-opencl.yml +++ b/.github/workflows/build-opencl.yml @@ -61,6 +61,11 @@ jobs: run: | choco install ninja + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Install OpenCL Headers and Libs id: install_opencl run: | diff --git a/.github/workflows/build-vulkan.yml b/.github/workflows/build-vulkan.yml index d2375b0141fb..b699f2a1723c 100644 --- a/.github/workflows/build-vulkan.yml +++ b/.github/workflows/build-vulkan.yml @@ -213,6 +213,11 @@ jobs: run: | choco install ninja + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Build id: cmake_build run: | diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index ad1a9de9a05f..2272ac35aefa 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -16,6 +16,10 @@ on: description: "Skip the s390x build target (useful for fast test runs that do not need the IBM Z runner)" type: boolean default: false + skip_ref_check: + description: "Skip the requirement to run from a tag (allows branch refs)" + type: boolean + default: false schedule: # Rebuild daily rather than on every push because it is expensive - cron: '12 4 * * *' @@ -38,6 +42,14 @@ jobs: source_tag: ${{ steps.srctag.outputs.name }} steps: + - name: Check manual run ref + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.skip_ref_check }} + run: | + if [[ "$GITHUB_REF_TYPE" != "tag" ]]; then + echo "::error::Manual runs of this workflow must be started from a tag" + exit 1 + fi + - name: Clone id: checkout uses: actions/checkout@v6 @@ -170,7 +182,7 @@ jobs: uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist # - name: Set up QEMU # if: ${{ contains(matrix.config.platforms, 'linux/amd64') }} diff --git a/.github/workflows/pr-video-demo-label.yml b/.github/workflows/pr-video-demo-label.yml index 9b3165fa22ab..f6f8567531c3 100644 --- a/.github/workflows/pr-video-demo-label.yml +++ b/.github/workflows/pr-video-demo-label.yml @@ -22,7 +22,7 @@ jobs: BODY: ${{ github.event.pull_request.body }} HAS_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'video demo') }} run: | - # sections written by demo:pr (see tools/ui/demo/cli.ts): the managed comment + # sections written by demo:pr (see ui/apps/chat/demo/cli.ts): the managed comment # markers, or a preview linking to a demo video uploaded for this PR has_demo=false if { grep -qF '' <<< "$BODY" && grep -qF '' <<< "$BODY"; } || diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4777f613ee7b..c918feb06916 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -130,7 +130,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: ccache uses: ggml-org/ccache-action@v1.2.24 @@ -196,7 +196,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Dependencies id: depends @@ -274,7 +274,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Dependencies id: depends @@ -381,7 +381,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Dependencies id: depends @@ -479,7 +479,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Set up JDK uses: actions/setup-java@v5 @@ -571,7 +571,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Build id: cmake_build @@ -624,7 +624,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Build id: cmake_build @@ -672,7 +672,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: ccache uses: ggml-org/ccache-action@v1.2.24 @@ -894,12 +894,17 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Install Ninja run: | choco install ninja + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: ccache uses: ggml-org/ccache-action@v1.2.24 with: @@ -1146,6 +1151,11 @@ jobs: run: | choco install ninja + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + # TODO: these jobs need to use llvm toolchain in order to utilize the ccache #- name: ccache # uses: ggml-org/ccache-action@v1.2.24 @@ -1460,7 +1470,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Dependencies id: depends @@ -1532,7 +1542,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Free up disk space uses: ggml-org/free-disk-space@v1.3.1 @@ -1647,7 +1657,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Dependencies id: depends diff --git a/.github/workflows/server-speculative.yml b/.github/workflows/server-speculative.yml index de247afb6fb7..e90eb21c4942 100644 --- a/.github/workflows/server-speculative.yml +++ b/.github/workflows/server-speculative.yml @@ -7,6 +7,40 @@ on: description: 'Commit SHA1 to build' required: false type: string + spec_methods: + description: 'Speculative methods to test' + required: true + default: 'compact' + type: choice + options: + - compact + - nightly + - all + push: + branches: + - master + paths: [ + '.github/workflows/server-speculative.yml', + 'common/speculative.*', + 'src/models/dflash*.cpp', + 'src/models/dspark.cpp', + 'src/models/eagle3.cpp', + 'src/models/lilicorr.cpp', + 'src/models/qwen35.cpp', + 'tools/server/tests/unit/test_spec_methods.py' + ] + pull_request: + types: [opened, synchronize, reopened] + paths: [ + '.github/workflows/server-speculative.yml', + 'common/speculative.*', + 'src/models/dflash*.cpp', + 'src/models/dspark.cpp', + 'src/models/eagle3.cpp', + 'src/models/lilicorr.cpp', + 'src/models/qwen35.cpp', + 'tools/server/tests/unit/test_spec_methods.py' + ] cache-mode: none permissions: @@ -56,8 +90,9 @@ jobs: - name: Test speculative decoding env: - SPEC_METHODS: compact - SPEC_MODEL_DIR: ${{ vars.SPEC_METHOD_MODEL_DIR || format('{0}/spec-models', runner.temp) }} + SPEC_METHODS: ${{ github.event.inputs.spec_methods || 'compact' }} + # pull requests from forks do not get repository variables + SPEC_MODEL_DIR: ${{ vars.SPEC_METHOD_MODEL_DIR || '/mnt/cache/spec-models' }} N_GPU_LAYERS: 99 run: | cd tools/server/tests diff --git a/.github/workflows/server.yml b/.github/workflows/server.yml index f3c577ec6d28..38231317ed3a 100644 --- a/.github/workflows/server.yml +++ b/.github/workflows/server.yml @@ -175,6 +175,11 @@ jobs: evict-old-files: 1d save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Build id: cmake_build shell: cmd diff --git a/.github/workflows/ui-build-self-hosted.yml b/.github/workflows/ui-build-self-hosted.yml index 0ba2eb983fc2..660786ff7f86 100644 --- a/.github/workflows/ui-build-self-hosted.yml +++ b/.github/workflows/ui-build-self-hosted.yml @@ -23,20 +23,20 @@ jobs: with: node-version: "24" # cache: "npm" - # cache-dependency-path: "tools/ui/package-lock.json" + # cache-dependency-path: "ui/apps/chat/package-lock.json" package-manager-cache: false - name: Install dependencies run: npm ci - working-directory: tools/ui + working-directory: ui/apps/chat - name: Build application run: npm run build - working-directory: tools/ui + working-directory: ui/apps/chat - name: Upload built UI uses: actions/upload-artifact@v6 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ retention-days: 1 diff --git a/.github/workflows/ui-build.yml b/.github/workflows/ui-build.yml index f229fcd04480..67fc2fadc9d7 100644 --- a/.github/workflows/ui-build.yml +++ b/.github/workflows/ui-build.yml @@ -37,26 +37,26 @@ jobs: with: node-version: "24" # cache: "npm" - # cache-dependency-path: "tools/ui/package-lock.json" + # cache-dependency-path: "ui/apps/chat/package-lock.json" package-manager-cache: false - name: Install dependencies run: npm ci - working-directory: tools/ui + working-directory: ui/apps/chat - name: Build application env: LLAMA_BUILD_NUMBER: ${{ steps.version.outputs.ui_version }} run: npm run build - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run PWA unit tests (versioned build output) run: npx vitest --project=unit --run tests/unit/pwa.spec.ts - working-directory: tools/ui + working-directory: ui/apps/chat - name: Upload built UI uses: actions/upload-artifact@v7 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ retention-days: 1 diff --git a/.github/workflows/ui-chat-publish.yml b/.github/workflows/ui-chat-publish.yml new file mode 100644 index 000000000000..193aa375fe78 --- /dev/null +++ b/.github/workflows/ui-chat-publish.yml @@ -0,0 +1,183 @@ +name: UI Chat Publish + +# Publishes Llama Chat to npm: @ggml-org/llama-chat (ui/apps/chat, the app and its CLI) and +# llama-chat (ui/apps/chat/alias, the short name for npx), always at the same version. +# +# The version in ui/apps/chat/package.json is the release, set by hand, as for @ggml-org/llama-ui +# in ui-lib-publish.yml. A commit that reaches master with a version npm does not have builds the +# app and publishes both packages; any other commit publishes nothing. Bump both package.json +# files in the PR that should ship. +# +# Auth: no npm token is stored here. The job exchanges its OIDC identity for one (npm trusted +# publishing) and signs the tarballs with provenance. One-time setup, before this can publish: on +# each of the two packages, Publishing settings, Trusted Publisher, GitHub Actions, with +# organization ggml-org, repository llama.cpp, workflow file ui-chat-publish.yml and Environment +# left blank. Until then the publish step fails on master; re-running the job publishes it. + +on: + workflow_dispatch: + inputs: + dry_run: + description: 'Build and pack, but do not publish' + required: false + type: boolean + default: false + push: + branches: + - master + paths: [ + '.github/workflows/ui-chat-publish.yml', + 'ui/apps/chat/package.json', + 'ui/apps/chat/alias/package.json' + ] + # a dry run for PRs that change what goes into the packages + pull_request: + types: [opened, synchronize, reopened] + paths: [ + '.github/workflows/ui-chat-publish.yml', + 'ui/apps/chat/package.json', + 'ui/apps/chat/alias/**', + 'ui/apps/chat/bin/**', + 'ui/apps/chat/cli/**' + ] + +cache-mode: none +permissions: + contents: read + id-token: write + +concurrency: + # never cancel a run mid-publish: a version half-published cannot be taken back + group: ${{ github.workflow }} + cancel-in-progress: false + +env: + APP_DIR: ui/apps/chat + ALIAS_DIR: ui/apps/chat/alias + VERSION_CHECK: ui/lib/ui/scripts/npm-version-check.mjs + +jobs: + publish: + name: Publish @ggml-org/llama-chat and llama-chat + if: github.repository == 'ggml-org/llama.cpp' + runs-on: ubuntu-26.04-arm + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + fetch-depth: 0 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + registry-url: 'https://registry.npmjs.org' + package-manager-cache: false + + - name: Check npm can publish with an OIDC token + run: | + node -e ' + const v = process.argv[1]; + const [major, minor] = v.split(".").map(Number); + if (major < 11 || (major === 11 && minor < 5)) { + console.error(`npm ${v} cannot publish with trusted publishing: 11.5.1 or newer is needed`); + process.exit(1); + } + ' "$(npm -v)" + + - name: Install dependencies + run: npm ci + working-directory: ${{ env.APP_DIR }} + + - name: Build the app + # the same build.json version as the UI that llama-server embeds, for the app's update check. + # This folder's .npmrc sets ignore-scripts, so npm never builds it: this step does. + run: LLAMA_BUILD_NUMBER="b$(git rev-list --count HEAD)" npm run build + working-directory: ${{ env.APP_DIR }} + + - name: Test the CLI and the alias version + run: npx vitest --project=unit --run tests/unit/cli.test.ts + working-directory: ${{ env.APP_DIR }} + + - name: Check what goes into the package + run: | + npm pack --dry-run --json > "$RUNNER_TEMP/pack.json" + node -e ' + const [{ files }] = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")); + const paths = files.map((file) => file.path); + const maps = paths.filter((path) => path.endsWith(".map")); + if (!paths.includes("dist/index.html")) { + console.error("dist/index.html is not in the package: nothing would be served"); + process.exit(1); + } + if (maps.length > 0) { + console.error(`source maps in the package: ${maps.join(", ")}`); + process.exit(1); + } + console.log(`${paths.length} files, no source maps`); + ' "$RUNNER_TEMP/pack.json" + working-directory: ${{ env.APP_DIR }} + + - name: Compare @ggml-org/llama-chat with npm + id: app + continue-on-error: ${{ github.event_name == 'pull_request' }} + run: node "$VERSION_CHECK" "$APP_DIR" + + - name: Compare llama-chat with npm + id: alias + continue-on-error: ${{ github.event_name == 'pull_request' }} + run: node "$VERSION_CHECK" "$ALIAS_DIR" + + # master only: npm's trusted publisher matches the repository and the workflow file, not the + # branch, so this condition is what keeps a manual run on a PR branch from publishing. + # The app goes first, since the alias depends on it at the same version. + - name: Publish @ggml-org/llama-chat + if: github.ref == 'refs/heads/master' && steps.app.outputs.should_publish == 'true' && inputs.dry_run != true + env: + TAG: ${{ steps.app.outputs.tag }} + run: npm publish --access public --provenance --ignore-scripts --tag "$TAG" + working-directory: ${{ env.APP_DIR }} + + - name: Publish llama-chat + if: github.ref == 'refs/heads/master' && steps.alias.outputs.should_publish == 'true' && inputs.dry_run != true + env: + TAG: ${{ steps.alias.outputs.tag }} + run: npm publish --access public --provenance --ignore-scripts --tag "$TAG" + working-directory: ${{ env.ALIAS_DIR }} + + - name: Report + if: always() + # values reach the shell through env, so a name from a PR's package.json cannot inject here + env: + APP: ${{ steps.app.outputs.name }}@${{ steps.app.outputs.version }} + APP_VERDICT: ${{ steps.app.outputs.verdict || 'not reached' }} + APP_NOTE: ${{ steps.app.outputs.note }} + ALIAS: ${{ steps.alias.outputs.name }}@${{ steps.alias.outputs.version }} + ALIAS_VERDICT: ${{ steps.alias.outputs.verdict || 'not reached' }} + ALIAS_NOTE: ${{ steps.alias.outputs.note }} + DRY: ${{ inputs.dry_run }} + EVENT: ${{ github.event_name }} + run: | + { + echo "### Llama Chat on npm" + echo + echo "| package | verdict | note |" + echo "| --- | --- | --- |" + echo "| \`$APP\` | \`$APP_VERDICT\` | $APP_NOTE |" + echo "| \`$ALIAS\` | \`$ALIAS_VERDICT\` | $ALIAS_NOTE |" + echo + if [ "$EVENT" = "pull_request" ] || [ "$DRY" = "true" ]; then echo "Dry run: nothing was published."; fi + } >> "$GITHUB_STEP_SUMMARY" + + - name: Mind the verdict + # a version going backwards is a mistake; an unchanged version is a package.json edit that + # is not a release, such as a dependency update + if: always() && github.event_name != 'pull_request' + env: + VERDICTS: ${{ steps.app.outputs.verdict }} ${{ steps.alias.outputs.verdict }} + run: | + case " $VERDICTS " in + *" stale "*) + echo "::error::a version in package.json is older than the one on npm" + exit 1 ;; + esac diff --git a/.github/workflows/ui-lib-publish.yml b/.github/workflows/ui-lib-publish.yml new file mode 100644 index 000000000000..0faf11c4d6ab --- /dev/null +++ b/.github/workflows/ui-lib-publish.yml @@ -0,0 +1,201 @@ +name: UI Lib Publish + +# Publishes @ggml-org/llama-ui, the library in ui/lib/ui, to npm. +# +# The version in ui/lib/ui/package.json is the release. A commit that reaches master with a +# version npm does not have builds the library and publishes it; a commit that changes the +# library without bumping it publishes nothing and says so on the run, which is the drift that +# let 0.3.0 sit a day behind master. Bump the version in the PR whose change should ship, and +# this workflow does the rest. +# +# Auth: no npm token is stored here. The job exchanges its OIDC identity for one (npm trusted +# publishing) and signs the tarball with a provenance attestation. release-publish.yml has done +# the same exchange on every push to master since it landed, its actions/attest step being the +# proof that this repository can be issued a token. +# +# One-time setup, before this can publish: on the package, Publishing settings, Trusted +# Publisher, GitHub Actions, with organization ggml-org, repository llama.cpp, workflow file +# 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. + +on: + workflow_dispatch: + inputs: + dry_run: + description: 'Build and pack, but do not publish' + required: false + type: boolean + default: false + push: + branches: + - master + paths: [ + '.github/workflows/ui-lib-publish.yml', + 'ui/lib/ui/**.*' + ] + # the advisory half, so a library change without a bump is annotated on the PR rather than + # discovered after the merge: the path filter keeps it off PRs that touch only Llama Chat + pull_request: + types: [opened, synchronize, reopened] + paths: [ + '.github/workflows/ui-lib-publish.yml', + 'ui/lib/ui/**.*' + ] + +cache-mode: none +permissions: + contents: read + id-token: write + +concurrency: + # never cancel a run mid-publish: a version half-published cannot be taken back. GitHub holds + # one pending run per group, so a newer push replaces an older queued one - no release is lost, + # as each run reads the version from its own commit. + group: ${{ github.workflow }} + cancel-in-progress: false + +env: + LIB_DIR: ui/lib/ui + +jobs: + publish: + name: Publish @ggml-org/llama-ui + if: github.repository == 'ggml-org/llama.cpp' + runs-on: ubuntu-26.04-arm + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + registry-url: 'https://registry.npmjs.org' + package-manager-cache: false + + - name: Check npm can publish with an OIDC token + run: | + npm -v + node -e ' + const v = process.argv[1]; + const [major, minor] = v.split(".").map(Number); + if (major < 11 || (major === 11 && minor < 5)) { + console.error(`npm ${v} cannot publish with trusted publishing: 11.5.1 or newer is needed`); + process.exit(1); + } + ' "$(npm -v)" + + - name: Install dependencies + run: npm ci + working-directory: ${{ env.LIB_DIR }} + + - name: Run type checking + run: npm run check + working-directory: ${{ env.LIB_DIR }} + + - name: Build the package and lint it + run: npm run prepack + working-directory: ${{ env.LIB_DIR }} + + - name: Compare the version with npm + id: version + # on a PR this is advisory and must not fail the job: a registry outage is not the + # contributor's mistake. On master the publish decision rests on the answer, so it fails. + continue-on-error: ${{ github.event_name == 'pull_request' }} + run: node scripts/npm-version-check.mjs + working-directory: ${{ env.LIB_DIR }} + + - name: Note a library change that ships no new version + if: github.event_name == 'pull_request' && always() && steps.version.outcome == 'success' && steps.version.outputs.should_publish != 'true' + env: + NOTE: ${{ steps.version.outputs.note }} + run: echo "::warning::$NOTE" + + - name: Publish + # master only. npm's trusted publisher matches on the repository and the workflow file, + # not the branch, so this condition is the only thing stopping a manual run from a PR + # branch - one that anyone with write access can start - from publishing code that no + # one reviewed. A dispatch on master remains the way to re-run a release. + if: github.ref == 'refs/heads/master' && steps.version.outputs.should_publish == 'true' && inputs.dry_run != true + # --ignore-scripts publishes the tarball prepack built and publint passed rather than + # rebuilding it here; --provenance is implied by trusted publishing and named to be + # explicit. A package published with nothing in it cannot be taken back, so refuse first. + env: + TAG: ${{ steps.version.outputs.tag }} + run: | + 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: Verify it landed + if: github.ref == 'refs/heads/master' && steps.version.outputs.should_publish == 'true' && inputs.dry_run != true + env: + NAME: ${{ steps.version.outputs.name }} + VERSION: ${{ steps.version.outputs.version }} + 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 + + - name: Report + if: always() + # every value reaches the shell through env, not through the script, so a package name + # from a PR's package.json cannot inject into this step + env: + NAME: ${{ steps.version.outputs.name || '@ggml-org/llama-ui' }} + VERSION: ${{ steps.version.outputs.version || 'unknown' }} + LATEST: ${{ steps.version.outputs.latest }} + VERDICT: ${{ steps.version.outputs.verdict || 'not reached' }} + NOTE: ${{ steps.version.outputs.note }} + SHOULD: ${{ steps.version.outputs.should_publish }} + DRY: ${{ inputs.dry_run }} + run: | + if [ "$DRY" = "true" ]; then published="no (dry run)" + elif [ "$SHOULD" = "true" ]; then published=yes + else published=no + fi + { + echo "### $NAME $VERSION" + echo + echo "| | |" + echo "| --- | --- |" + echo "| npm latest was | ${LATEST:-nothing published yet} |" + echo "| verdict | \`$VERDICT\` |" + echo "| published | $published |" + echo + echo "> $NOTE" + } >> "$GITHUB_STEP_SUMMARY" + + - name: Mind the verdict + if: always() && github.event_name != 'pull_request' && steps.version.outcome == 'success' + # a version going backwards is a mistake; a version not bumped is usually one too, but it + # is also what a stories-only commit looks like, so that only fails the run when the + # repository variable UI_LIB_PUBLISH_FAIL_ON_UNBUMPED is set to true + env: + NOTE: ${{ steps.version.outputs.note }} + VERDICT: ${{ steps.version.outputs.verdict }} + FAIL_ON_UNBUMPED: ${{ vars.UI_LIB_PUBLISH_FAIL_ON_UNBUMPED }} + run: | + case "$VERDICT" in + stale) + echo "::error::$NOTE" + exit 1 ;; + published) + if [ "$FAIL_ON_UNBUMPED" = "true" ]; then + echo "::error::$NOTE" + exit 1 + fi + echo "::warning::$NOTE" ;; + esac diff --git a/.github/workflows/ui-publish.yml b/.github/workflows/ui-publish.yml index d77b899b2302..fc624e3e8241 100644 --- a/.github/workflows/ui-publish.yml +++ b/.github/workflows/ui-publish.yml @@ -33,15 +33,15 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ run-id: ${{ inputs.run_id }} github-token: ${{ github.token }} - name: Create distribution archive run: | - tar -czf dist.tar.gz -C tools/ui/dist . + tar -czf dist.tar.gz -C ui/apps/chat/dist . sha256sum dist.tar.gz > dist.tar.gz.sha256 - mv dist.tar.gz dist.tar.gz.sha256 tools/ui/dist/ + mv dist.tar.gz dist.tar.gz.sha256 ui/apps/chat/dist/ - name: Install Hugging Face Hub CLI run: pip install -U huggingface_hub @@ -52,12 +52,12 @@ jobs: - name: Sync built files to Hugging Face bucket (version tag) run: | # Upload the built files to the Hugging Face bucket under the release version - hf buckets sync tools/ui/dist hf://buckets/ggml-org/${{ env.HF_BUCKET_NAME }}/${{ inputs.version_tag }} --delete --quiet + hf buckets sync ui/apps/chat/dist hf://buckets/ggml-org/${{ env.HF_BUCKET_NAME }}/${{ inputs.version_tag }} --delete --quiet - name: Sync built files to Hugging Face bucket (latest) run: | # Also upload to the 'latest' directory for fallback downloads - hf buckets sync tools/ui/dist hf://buckets/ggml-org/${{ env.HF_BUCKET_NAME }}/latest --delete --quiet + hf buckets sync ui/apps/chat/dist hf://buckets/ggml-org/${{ env.HF_BUCKET_NAME }}/latest --delete --quiet - name: Verify upload run: | diff --git a/.github/workflows/ui-self-hosted.yml b/.github/workflows/ui-self-hosted.yml index 93b7805f18d9..346f1cfb4b12 100644 --- a/.github/workflows/ui-self-hosted.yml +++ b/.github/workflows/ui-self-hosted.yml @@ -17,7 +17,8 @@ on: paths: [ '.github/workflows/ui-self-hosted.yml', '.github/workflows/ui-build-self-hosted.yml', - 'tools/ui/**.*', + 'ui/apps/chat/**.*', + 'ui/lib/ui/**.*', 'tools/server/tests/**.*' ] pull_request: @@ -25,7 +26,8 @@ on: paths: [ '.github/workflows/ui-self-hosted.yml', '.github/workflows/ui-build-self-hosted.yml', - 'tools/ui/**.*', + 'ui/apps/chat/**.*', + 'ui/lib/ui/**.*', 'tools/server/tests/**.*' ] @@ -67,33 +69,33 @@ jobs: - name: Install dependencies id: setup run: npm ci - working-directory: tools/ui + working-directory: ui/apps/chat - name: Download built UI artifacts uses: actions/download-artifact@v6 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ - name: Run type checking if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run check - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run linting if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run lint - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run Client tests if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run test:client - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run Unit tests if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run test:unit - working-directory: tools/ui + working-directory: ui/apps/chat e2e-tests: name: E2E Tests @@ -109,25 +111,25 @@ jobs: - name: Install dependencies id: setup run: npm ci - working-directory: tools/ui + working-directory: ui/apps/chat - name: Download built UI artifacts uses: actions/download-artifact@v6 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ - name: Build Storybook if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run build-storybook - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run UI tests if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run test:ui -- --testTimeout=60000 - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run E2E tests if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run test:e2e - working-directory: tools/ui + working-directory: ui/apps/chat diff --git a/.github/workflows/ui-storybook.yml b/.github/workflows/ui-storybook.yml new file mode 100644 index 000000000000..fe922b1a2d80 --- /dev/null +++ b/.github/workflows/ui-storybook.yml @@ -0,0 +1,84 @@ +name: UI Storybook + +# Builds Llama UI and Llama Chat's Storybook (ui/apps/chat) and publishes it to its Hugging Face Space +# whenever the UI changes on master, so the Space always shows the latest build. + +on: + workflow_dispatch: + push: + branches: + - master + paths: [ + '.github/workflows/ui-storybook.yml', + 'ui/apps/chat/**', + 'ui/lib/ui/**' + ] + +cache-mode: none +permissions: + contents: read + +# only the newest build matters: a newer push replaces a deploy still in progress +concurrency: + group: ${{ github.workflow }} + cancel-in-progress: true + +jobs: + deploy: + name: Deploy to Hugging Face Spaces + if: github.repository == 'ggml-org/llama.cpp' + runs-on: hf-jobs-cpu-upgrade:ubuntu26_04 + + env: + HF_SPACE: ${{ vars.HF_SPACE_UI_STORYBOOK || 'ggml-org/llama-ui-storybook' }} + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + package-manager-cache: false + + - name: Install dependencies + run: npm ci + working-directory: ui/apps/chat + + - name: Build Storybook + run: npm run build-storybook + working-directory: ui/apps/chat + + - name: Write the Space card + run: | + cat > ui/apps/chat/storybook-static/README.md << EOF + --- + title: Llama UI Storybook + emoji: 🦙 + colorFrom: gray + colorTo: gray + sdk: static + pinned: false + --- + + The Storybook of Llama UI and Llama Chat, built from [ggml-org/llama.cpp](https://github.com/ggml-org/llama.cpp) (\`ui/apps/chat\`) at ${GITHUB_SHA}. + EOF + + - name: Install Hugging Face Hub CLI + run: | + sudo apt-get update + sudo apt-get install -y python3 python3-venv + python3 -m venv .venv-hf + .venv-hf/bin/pip install -U huggingface_hub==1.28.0 + + - name: Upload to the Space + env: + # a token with write access to the Space; HF_TOKEN_UI_STATIC_OUTPUT if that one has it + HF_TOKEN: ${{ secrets.HF_TOKEN_UI_STORYBOOK || secrets.HF_TOKEN_UI_STATIC_OUTPUT }} + run: | + # --delete '*' removes files the new build no longer has; the Space's .gitattributes is always kept + .venv-hf/bin/hf upload "$HF_SPACE" ui/apps/chat/storybook-static . \ + --repo-type space \ + --delete '*' \ + --commit-message "Storybook from ggml-org/llama.cpp@${GITHUB_SHA::10}" diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index c5c6a32a8177..10d7ed0ed5e4 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -13,7 +13,8 @@ on: paths: [ '.github/workflows/ui.yml', '.github/workflows/ui-build.yml', - 'tools/ui/**.*', + 'ui/apps/chat/**.*', + 'ui/lib/**.*', 'tools/server/tests/**.*' ] pull_request: @@ -21,7 +22,8 @@ on: paths: [ '.github/workflows/ui.yml', '.github/workflows/ui-build.yml', - 'tools/ui/**.*', + 'ui/apps/chat/**.*', + 'ui/lib/**.*', 'tools/server/tests/**.*' ] @@ -66,46 +68,87 @@ jobs: with: node-version: "24" # cache: "npm" - # cache-dependency-path: "tools/ui/package-lock.json" + # cache-dependency-path: "ui/apps/chat/package-lock.json" package-manager-cache: false - name: Download built UI artifacts uses: actions/download-artifact@v6 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ - name: Install dependencies id: setup if: ${{ steps.node.conclusion == 'success' }} run: npm ci - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run type checking if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run check - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run linting if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run lint - working-directory: tools/ui + working-directory: ui/apps/chat + + - name: Check DESIGN.md is current with the tokens + if: ${{ always() && steps.setup.conclusion == 'success' }} + run: npm run check:design + working-directory: ui/apps/chat - name: Install Playwright browsers id: playwright if: ${{ always() && steps.setup.conclusion == 'success' }} run: npx playwright install --with-deps - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run Client tests if: ${{ always() && steps.playwright.conclusion == 'success' }} run: npm run test:client - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run Unit tests (uses pre-built dist/ from ui-build) if: ${{ always() && steps.playwright.conclusion == 'success' }} run: npm run test:unit - working-directory: tools/ui + working-directory: ui/apps/chat + + lib-checks: + name: Library 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/ui + + - name: Run type checking + run: npm run check + working-directory: ui/lib/ui + + - name: Install Playwright browsers + run: npx playwright install --with-deps chromium + working-directory: ui/lib/ui + + # the unit tests and the Storybook stories (ui/lib/ui/tests/stories), which run as tests in Chromium + - name: Run tests + run: npm test + working-directory: ui/lib/ui + + - name: Build the package + run: npm run prepack + working-directory: ui/lib/ui e2e-tests: name: E2E Tests @@ -124,38 +167,38 @@ jobs: with: node-version: "24" # cache: "npm" - # cache-dependency-path: "tools/ui/package-lock.json" + # cache-dependency-path: "ui/apps/chat/package-lock.json" package-manager-cache: false - name: Install dependencies id: setup if: ${{ steps.node.conclusion == 'success' }} run: npm ci - working-directory: tools/ui + working-directory: ui/apps/chat - name: Download built UI artifacts (reuses ui-build) uses: actions/download-artifact@v6 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ - name: Install Playwright browsers id: playwright if: ${{ always() && steps.setup.conclusion == 'success' }} run: npx playwright install --with-deps - working-directory: tools/ui + working-directory: ui/apps/chat - name: Build Storybook if: ${{ always() && steps.playwright.conclusion == 'success' }} run: npm run build-storybook - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run UI tests if: ${{ always() && steps.playwright.conclusion == 'success' }} run: npm run test:ui -- --testTimeout=60000 - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run E2E tests (uses pre-built dist/ from ui-build) if: ${{ always() && steps.playwright.conclusion == 'success' }} run: npm run test:e2e - working-directory: tools/ui + working-directory: ui/apps/chat diff --git a/AUTHORS b/AUTHORS index 96ca4c1d9bff..721a0a1a43de 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,4 +1,4 @@ -# date: Wed Nov 4 12:03:31 EET 2026 +# date: Mon Nov 16 10:05:56 EET 2026 # this file is auto-generated by scripts/gen-authors.sh Нияз Гарифзянов <112617865+garrnizon@users.noreply.github.com> @@ -43,7 +43,9 @@ Aarni Koskela Aaron Miller Aaron Teo <57927438+taronaeo@users.noreply.github.com> Aaron Teo +Aaron Thomas <84493696+arxhr007@users.noreply.github.com> Aaryaman Vasishta +Aayan Karmali <44980366+StockerMC@users.noreply.github.com> Abheek Gulati abhijain1204fujitsu <139222713+abhijain1204fujitsu@users.noreply.github.com> Abhijit Ramesh @@ -112,10 +114,12 @@ Aleksander Grygier Aleksander Grygier Aleksander Grygier Aleksei Nikiforov <103434461+AlekseiNikiforovIBM@users.noreply.github.com> +Alen Požun Alessandro de Oliveira Faria (A.K.A.CABELO) Alessandro98-git <61804547+Alessandro98-git@users.noreply.github.com> Alex <18387287+wadealexc@users.noreply.github.com> Alex <59368173+AlexGabbia@users.noreply.github.com> +Alex Alex Alex Azarov Alex Azarov @@ -132,6 +136,7 @@ Alex Trotta <44127594+Ahajha@users.noreply.github.com> Alex Tuddenham <61622354+AlexsCode@users.noreply.github.com> Alex von Gluck IV Alex Wu +Alex-JP-93 alex-spacemit Alexander Batischev Alexander Heisler <126129661+heislera763@users.noreply.github.com> @@ -143,6 +148,7 @@ Alexis Williams alexpinel <93524949+alexpinel@users.noreply.github.com> Alfred Ali Chraghi <63465728+alichraghi@users.noreply.github.com> +Ali F. Al-Ramadan <55710790+aalramadan@users.noreply.github.com> Ali Nehzat Ali Tariq Ali Tariq @@ -158,6 +164,7 @@ Aman Karki Aman Karki amd-dwang amd-lalithnc +AMIR <127450356+amirthn6533@users.noreply.github.com> Amir amirai21 <89905406+amirai21@users.noreply.github.com> AmirAli Mirian <37371367+amiralimi@users.noreply.github.com> @@ -213,6 +220,7 @@ Antoine Viallon Anton I Anton Mitkov Anton Mitkov +Anton Sokolchenko Antonis Makropoulos anubhavfujitsu Anudit Nagar @@ -233,10 +241,12 @@ arlo-phoenix <140345165+arlo-phoenix@users.noreply.github.com> Armen Kaleshian Arsen Arutunan <58118221+limloop@users.noreply.github.com> Arseniy Obolenskiy +ArshM17-NV Artem Artem Zinnatullin Artyom Lebedev aryantandon01 <80969509+aryantandon01@users.noreply.github.com> +Asahi-Prv <246092086+Asahi-Prv@users.noreply.github.com> Asahi-Prv asbelin <71226900+asbelin@users.noreply.github.com> Asbjørn Olling @@ -258,6 +268,7 @@ AustinMroz AUTOMATIC1111 <16777216c@gmail.com> automaticcat awatuna <23447591+awatuna@users.noreply.github.com> +Awss b4b4o Bach Le BADR @@ -351,6 +362,7 @@ CarterLi999 <664681047@qq.com> Casey Primozic Casey Primozic CausalLM <148736309+CausalLM@users.noreply.github.com> +CC <65151926+realMoana@users.noreply.github.com> ccbinn cduk <19917266+cduk@users.noreply.github.com> cebtenzzre @@ -379,6 +391,7 @@ Cheng Shao Chenguang Li <757486878@qq.com> Chenguang Li <87689256+noemotiovon@users.noreply.github.com> chiheb ben cheikh <100644963+ChihebBENCHEIKH1@users.noreply.github.com> +chinmaykamjith001 Chipmunk <101038159+CHIPMUNK-T0T@users.noreply.github.com> chiranko <96988916+chiranko@users.noreply.github.com> Chris Danis @@ -434,6 +447,7 @@ crasm crat0z <11581854+crat0z@users.noreply.github.com> CRD716 CrispStrobe <154636388+CrispStrobe@users.noreply.github.com> +Cristian Adam Cristiano Pinto <140563307+crowmoed@users.noreply.github.com> crsawyer <7572190+crsawyer@users.noreply.github.com> Csaba Kecskemeti @@ -527,6 +541,7 @@ Djip007 <3705339+Djip007@users.noreply.github.com> Djip007 dm4 dm4 +Dmitrii Panchev Dmitry Atamanov Dmytro Minochkin Dmytro Romanov @@ -567,6 +582,7 @@ Ed Addario <29247825+EAddario@users.noreply.github.com> Ed Lee Ed Lepedus Eddie-Wang +eddiechen Eden eduardopessin <100053075+eduardopessin@users.noreply.github.com> Edward Taylor @@ -598,6 +614,7 @@ Erik Winter <93544977+ewintr@users.noreply.github.com> Ervin Áron Tasnádi Esko Toivonen Ethan Guo +Ethan Lin Ethan Turner Ettore Di Giacinto EugeoSynthesisThirtyTwo @@ -625,6 +642,7 @@ fanyang Farbod Bijary <110523279+farbodbj@users.noreply.github.com> Fathi Boudra Fattire <528174+fat-tire@users.noreply.github.com> +Feiteng felix Felix Felix Ye @@ -632,6 +650,7 @@ fengerhu1 <2748250768@qq.com> feni6 fidoriel <49869342+fidoriel@users.noreply.github.com> fiesh +figkcoci-debug FINAL-Bench Finn Voorhees Firat @@ -646,6 +665,7 @@ Foad Abo Dahood <32059146+masterFoad@users.noreply.github.com> Folko-Ven <71110216+Folko-Ven@users.noreply.github.com> forforever73 <63285796+forforever73@users.noreply.github.com> Foul-Tarnished <107711110+Foul-Tarnished@users.noreply.github.com> +fox5611 <66219952+fox5611@users.noreply.github.com> Francisco Herrera Francisco Melo <43780565+francis2tm@users.noreply.github.com> Francois Dugast @@ -709,6 +729,7 @@ GiviMAD gliptic gn64 goerch +Gotya-OFFCIAL Govlzkoy grahameth <96447521+grahameth@users.noreply.github.com> Gregor Jasny @@ -749,6 +770,7 @@ Haowei Wu Haoxiang Fei Harald Fernengel Harapan Rachman +Harkanwal Bedi Harkirat Gill HarrisonSec Hatsune Miku <129688334+at8u@users.noreply.github.com> @@ -768,6 +790,7 @@ Henrik Forstén Henry Linjamäki Henry Linjamäki Henry147147 <44851451+Henry147147@users.noreply.github.com> +Hera <58063257+hera2019@users.noreply.github.com> Herman Semenoff Herman Semenov Hesen Peng @@ -846,6 +869,7 @@ Imad Saddik <79410781+ImadSaddik@users.noreply.github.com> iMil Incarnas <119618389+bit-incarnas@users.noreply.github.com> InflexCZE +Iñigo Imaz <49730431+inimaz@users.noreply.github.com> Intel AI Get-to Market Customer Success and Solutions intelmatt <61025942+intelmatt@users.noreply.github.com> iohub @@ -857,7 +881,9 @@ IsaacDynamo <61521674+IsaacDynamo@users.noreply.github.com> Ishaan Gandhi iSma Ismail <115064057+AlrIsmail@users.noreply.github.com> +IsNot <209144869@qq.com> issixx <46835150+issixx@users.noreply.github.com> +Iswarya Alex <47045679+iswaryaalex@users.noreply.github.com> itsnotoger <19309683+itsnotoger@users.noreply.github.com> itterative <190138728+itterative@users.noreply.github.com> Ivan @@ -888,6 +914,7 @@ James Francis <6763899+JamesFranc@users.noreply.github.com> James O'Leary <65884233+jpohhhh@users.noreply.github.com> James Reynolds jameswu2014 <545426914@qq.com> +JamieBordoni Jan Boon Jan Boon Jan Ekström @@ -956,8 +983,10 @@ Jinyang He jinzihao Jiří Podivín <66251151+jpodivin@users.noreply.github.com> Jiří Sejkora +Jiří Svítil <32205472+mistrjirka@users.noreply.github.com> Jiwoong Song <55657581+jwsong98@users.noreply.github.com> JJJYmmm <92386084+JJJYmmm@users.noreply.github.com> +jjperry69 jklincn <985765408@qq.com> jklincn JM Robles @@ -970,6 +999,7 @@ Joe Rowell Joe Todd joecryptotoo <80373433+joecryptotoo@users.noreply.github.com> Joel +Joel Fernandes Johan Johannes Gäßler Johannes Rudolph @@ -988,6 +1018,7 @@ Jonas J <111707981+John-194@users.noreply.github.com> Jonas Jankaitis <111707981+John-194@users.noreply.github.com> Jonas Wunderlich <32615971+jonas-w@users.noreply.github.com> Jonathan <47618606+jbuchananr@users.noreply.github.com> +Jonathan Buck Jonathan Clohessy Jonathan Graehl <99024+graehl@users.noreply.github.com> Jorge A <161275481+jorgealias@users.noreply.github.com> @@ -1097,6 +1128,7 @@ klosax <131523366+klosax@users.noreply.github.com> KnightYao KokerZhou <111279477+KokerZhou@users.noreply.github.com> Kolen Cheung +Kong Jiale <2049447146@qq.com> kononnable Konrad Moren konradmb @@ -1167,6 +1199,7 @@ li-lizhe <82501526+li-lizhe@users.noreply.github.com> liangliangchang liminfei-amd <91481003+liminfei-amd@users.noreply.github.com> limitedAtonement +Lines lingyezhixing <144504450+lingyezhixing@users.noreply.github.com> linsen458-spec Linux User @@ -1227,6 +1260,7 @@ makomk manayang manikbhandari Manuel <44313466+makuche@users.noreply.github.com> +ManuelPDM <153872964+ManuelPDM@users.noreply.github.com> maor-ps <154728172+maor-ps@users.noreply.github.com> Maphist0 <28743569+Maphist0@users.noreply.github.com> Marc Köhlbrugge @@ -1336,6 +1370,7 @@ Michael Hueschen Michael Kesper Michael Klimenko Michael Lamothe +Michael Paulauski Michael Podvitskiy Michael Potter Michael Taylor <162068037+mctylr-gh@users.noreply.github.com> @@ -1455,6 +1490,7 @@ Nikolay Popov <131475237+npopov-vst@users.noreply.github.com> Nils Gladitz Nindaleth ningshanwutuobang +Nisbenz Noah <99681487+NoahOksuz@users.noreply.github.com> nold nopperl <54780682+nopperl@users.noreply.github.com> @@ -1462,6 +1498,7 @@ nullname Nuno nuri nusu-github <29514220+nusu-github@users.noreply.github.com> +nv-vankit <162085734+nv-vankit@users.noreply.github.com> nwyin o7si <32285332+o7si@users.noreply.github.com> Oğuzhan Akkaya @@ -1485,6 +1522,7 @@ oobabooga opparco Ori Pekelman Oscar Barenys +Oscar M. Herrera OSecret <135510162+OLSecret@users.noreply.github.com> ostix360 <55257054+ostix360@users.noreply.github.com> Ouadie EL FAROUKI @@ -1611,6 +1649,7 @@ Raj Hammeer Singh Hada Rajendra Matcha Ralph Soika Raman Shinde +Ramzi <146260554+rmz-24@users.noreply.github.com> Rand Xie Randall Fitzgerald Random Fly @@ -1651,6 +1690,7 @@ Rich Dougherty Richard Richard Davison Richard Kiss +Richard Palethorpe Richard Roberson RichardScottOZ Rick G <26732651+TheFlipbook@users.noreply.github.com> @@ -1695,6 +1735,7 @@ Roni Ronny Brendel Ronny Brendel Ronsor +Roshan Kumar <52444089+roshankumarg529@users.noreply.github.com> Rotem Dan Rowan Hart rspOverflow <217881046+rspOverflow@users.noreply.github.com> @@ -1727,9 +1768,11 @@ Saba Fallah <10401143+sfallah@users.noreply.github.com> Saba Fallah Sachin Desai Sachin Sharma +Saejin Kim-Heinert Safi Ullah safranowith Said Taghadouini <84044788+staghado@users.noreply.github.com> +SaidSultani <62264302+SaidSultani@users.noreply.github.com> Sait Furkan Teke <35101659+stfurkan@users.noreply.github.com> SakuraUmi Salvador E. Tropea @@ -1754,6 +1797,7 @@ Sang-Kil Park Sanjay Ahari Sarah Wu Sarah Wu +sargentmajord Sascha Rogmann <59577610+srogmann@users.noreply.github.com> sasha0552 Satinder Grewal @@ -1786,6 +1830,7 @@ Sergiu <8598216+mzsergiu@users.noreply.github.com> serhii-nakon <57632032+serhii-nakon@users.noreply.github.com> Sertaç Özercan <852750+sozercan@users.noreply.github.com> seryogakovalyov +Seungjun Bae Seungmin Kim <8457324+ehfd@users.noreply.github.com> SeungWon Jeong <65549245+redlion0929@users.noreply.github.com> Seyoung Jeong @@ -1871,6 +1916,7 @@ SmartestWashingMachine smugman-dot SnA1lGo <44647694+skrandy@users.noreply.github.com> snadampal <87143774+snadampal@users.noreply.github.com> +Sofian Elmotiem SoftwareRenderer <138734813+SoftwareRenderer@users.noreply.github.com> Someone Someone Serge @@ -1886,6 +1932,7 @@ sprayandwipe Sreeram SRHMorris <69468379+SRHMorris@users.noreply.github.com> Srihari-mcw <96763064+Srihari-mcw@users.noreply.github.com> +Srijan Keshri <212402043+arcusbuilds@users.noreply.github.com> Srinivas Billa srkizer ssweens <1149151+ssweens@users.noreply.github.com> @@ -1919,6 +1966,7 @@ Sutou Kouhei Svetlozar Georgiev <55534064+sgeor255@users.noreply.github.com> Swigler <124839156+Swigler@users.noreply.github.com> swittk +sxq <18856096915@163.com> SXX SXX Tai Duc Nguyen @@ -2044,6 +2092,7 @@ Ulrich Drepper unbounded Unbug Lee unraido <127105806+unraido@users.noreply.github.com> +usrlocalben uvos uvos uvos @@ -2084,6 +2133,7 @@ vk <89937361+itsvedantkumar@users.noreply.github.com> Vlad Vladimir Vladimir Malyutin +Vladimir Sotnikov Vladimir Vuksanovic <109677816+vvuksanovic@users.noreply.github.com> Vladimir Zorin Vladislav @@ -2139,6 +2189,7 @@ Wroclaw wsbagnsv1 Wu Jian Ping Wu Jian Ping +WuXin wwoodsTM <104587230+wwoodsTM@users.noreply.github.com> Wyatt Caldwell <218154709+Detensable@users.noreply.github.com> wzy <32936898+Freed-Wu@users.noreply.github.com> @@ -2162,6 +2213,7 @@ Xinpeng Dou <15529241576@163.com> Xinpeng Dou <81913537+Dou-Git@users.noreply.github.com> xloem <0xloem@gmail.com> xris99 <79798089+xris99@users.noreply.github.com> +Xuan Son Nguyen Xuan Son Nguyen Xuan-Son Nguyen Xuan-Son Nguyen @@ -2247,6 +2299,7 @@ zhangrunda zhangtao2-1 <478679312@qq.com> ZHAOKAI WANG Zhaolun Yin <129580161+ZhaolunYin@users.noreply.github.com> +zhaoyshine <30611065+zhaoyshine@users.noreply.github.com> Zheng.Deng <32841220+dengzheng-cloud@users.noreply.github.com> zhentaoyu Zhenwei Jin <109658203+kylo5aby@users.noreply.github.com> diff --git a/CMakeLists.txt b/CMakeLists.txt index 30aed5c914a9..7be920fbb377 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -134,7 +134,7 @@ option(LLAMA_BUILD_TOOLS "llama: build tools" option(LLAMA_BUILD_EXAMPLES "llama: build examples" ${LLAMA_STANDALONE}) option(LLAMA_BUILD_SERVER "llama: build server example" ${LLAMA_STANDALONE}) option(LLAMA_BUILD_APP "llama: build the unified binary" ${LLAMA_STANDALONE}) -option(LLAMA_BUILD_UI "llama: build the embedded Web UI for server" OFF) +option(LLAMA_BUILD_UI "llama: build Llama Chat, the embedded chat app, for server" OFF) option(LLAMA_USE_PREBUILT_UI "llama: use prebuilt UI from HF Bucket when available" ON) option(LLAMA_CONNECT "llama: include the llama-connect tool (downloads a prebuilt binary)" OFF) diff --git a/CODEOWNERS b/CODEOWNERS index f34a07f02255..af0553ac4fdc 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -102,7 +102,7 @@ /tools/rpc/ @ggml-org/ggml-rpc /tools/server/* @ggml-org/llama-server # no subdir /tools/server/tests/ @ggml-org/llama-server -/tools/ui/ @ggml-org/llama-ui +/ui/ @ggml-org/llama-ui /tools/tokenize/ @ggerganov /tools/tts/ @ggerganov /vendor/ @ggerganov diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 59ec3f311b5d..5b6327d11bc6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,6 +16,8 @@ The project differentiates between 3 levels of contributors: > > Detailed information regarding permissible and restricted uses of AI can be found in the [AGENTS.md](AGENTS.md) file. +### Requirements + If AI is used to generate any portion of the code, contributors must adhere to the following requirements: 1. Explicitly disclose the manner in which AI was employed. @@ -24,6 +26,16 @@ If AI is used to generate any portion of the code, contributors must adhere to t 4. Be prepared to explain every line of code you submit when asked about it by a maintainer. 5. It is strictly prohibited to use AI to write your posts for you (bug reports, feature requests, pull request descriptions, Github discussions, responding to humans, ...). +### Checklist + +> [!IMPORTANT] +> +> **If you use AI, do all of the following:** +> +> 1. **Make sure [AGENTS.md](AGENTS.md) is loaded into your agent's context.** Skipping this step is one of the most common reasons PRs get rejected. +> 2. **Search for related discussions, PRs and issues** to get the broader context before writing any code. +> 3. **Run a local review pass before pushing anything**, using the [`code-review`](skills/code-review/SKILL.md) skill, once the change is implemented. Fix what it finds. + For more info, please refer to the [AGENTS.md](AGENTS.md) file. # Pull requests (for contributors & collaborators) diff --git a/README.md b/README.md index 80b73cc528fa..8f2b10141540 100644 --- a/README.md +++ b/README.md @@ -7,16 +7,22 @@ LLM inference in C/C++ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) -[![Release](https://img.shields.io/github/v/release/ggml-org/llama.cpp?filter=v*&color=brightgreen)](https://github.com/ggml-org/llama.cpp/releases?q=tag:v1) +[![Release](https://img.shields.io/github/v/release/ggml-org/llama.cpp?color=brightgreen)](https://github.com/ggml-org/llama.cpp/releases?q=tag:v1) [![Nightly](https://img.shields.io/github/v/release/ggml-org/llama.cpp?label=nightly&filter=b*&color=orange)](https://github.com/ggml-org/llama.cpp/releases?q=b) [![Server](https://img.shields.io/github/actions/workflow/status/ggml-org/llama.cpp/server.yml?label=Server)](https://github.com/ggml-org/llama.cpp/actions/workflows/server.yml) [![Docker](https://img.shields.io/github/actions/workflow/status/ggml-org/llama.cpp/docker.yml?label=Docker)](https://github.com/ggml-org/llama.cpp/actions/workflows/docker.yml) [![Winget](https://img.shields.io/github/actions/workflow/status/ggml-org/llama.cpp/winget.yml?label=Winget)](https://github.com/ggml-org/llama.cpp/actions/workflows/winget.yml) -[ggml](https://github.com/ggml-org/ggml) / [ops](https://github.com/ggml-org/llama.cpp/blob/master/docs/ops.md) / [maintainer PRs](https://github.com/ggml-org/llama.cpp/pulls?q=is%3Apr%20is%3Aopen%20draft%3AFalse%20(author%3Asanmai%20OR%20author%3Argerganov%20OR%20author%3AKitaitiMakoto%20OR%20author%3Adanbev%20OR%20author%3Aaldehir%20OR%20author%3Amax-krasnyansky%20OR%20author%3ACISC%20OR%20author%3Aggerganov%20OR%20author%3Aam17an%20OR%20author%3Ajhen0409%20OR%20author%3Abartowski1182%20OR%20author%3Anikwen%20OR%20author%3Ahipudding%20OR%20author%3Aravi9%20OR%20author%3AServeurpersoCom%20OR%20author%3Athelittlefireman%20OR%20author%3Apwilkin%20OR%20author%3Areeselevine%20OR%20author%3Angxson%20OR%20author%3Ajeffbolznv%20OR%20author%3Amarty1885%20OR%20author%3A0cc4m%20OR%20author%3ATitaniumtown%20OR%20author%3Aangt%20OR%20author%3AIMbackK%20OR%20author%3Aarthw%20OR%20author%3AJohannesGaessler%20OR%20author%3AORippler%20OR%20author%3Aruixiang63%20OR%20author%3Axctan%20OR%20author%3AmasterFoad%20OR%20author%3Aallozaur%20OR%20author%3AAndreas-Krebbel%20OR%20author%3Ayomaytk%20OR%20author%3Aaendk%20OR%20author%3Awine99%20OR%20author%3Agaugarg-nv%20OR%20author%3Ataronaeo%20OR%20author%3Aforforever73%20OR%20author%3Achaxu01%20OR%20author%3Alhez%20OR%20author%3AAlekseiNikiforovIBM%20OR%20author%3Anetrunnereve%20OR%20author%3Afairydreaming%20OR%20author%3Aynankani)%20sort%3Aupdated-desc) / [dev stats](https://github.com/ggml-org/llama.cpp-dev) / [lib llama API](https://github.com/ggml-org/llama.cpp/issues/9289) / [llama-server REST API](https://github.com/ggml-org/llama.cpp/issues/9291) +[v1.0.0](https://huggingface.co/blog/ggml-org/llama-cpp-v1) / [ggml](https://github.com/ggml-org/ggml) / [ops](https://github.com/ggml-org/llama.cpp/blob/master/docs/ops.md) / [maintainer PRs](https://github.com/ggml-org/llama.cpp/pulls?q=is%3Apr%20is%3Aopen%20draft%3AFalse%20(author%3Asanmai%20OR%20author%3Argerganov%20OR%20author%3AKitaitiMakoto%20OR%20author%3Adanbev%20OR%20author%3Aaldehir%20OR%20author%3Amax-krasnyansky%20OR%20author%3ACISC%20OR%20author%3Aggerganov%20OR%20author%3Aam17an%20OR%20author%3Ajhen0409%20OR%20author%3Abartowski1182%20OR%20author%3Anikwen%20OR%20author%3Ahipudding%20OR%20author%3Aravi9%20OR%20author%3AServeurpersoCom%20OR%20author%3Athelittlefireman%20OR%20author%3Apwilkin%20OR%20author%3Areeselevine%20OR%20author%3Angxson%20OR%20author%3Ajeffbolznv%20OR%20author%3Amarty1885%20OR%20author%3A0cc4m%20OR%20author%3ATitaniumtown%20OR%20author%3Aangt%20OR%20author%3AIMbackK%20OR%20author%3Aarthw%20OR%20author%3AJohannesGaessler%20OR%20author%3AORippler%20OR%20author%3Aruixiang63%20OR%20author%3Axctan%20OR%20author%3AmasterFoad%20OR%20author%3Aallozaur%20OR%20author%3AAndreas-Krebbel%20OR%20author%3Ayomaytk%20OR%20author%3Aaendk%20OR%20author%3Awine99%20OR%20author%3Agaugarg-nv%20OR%20author%3Ataronaeo%20OR%20author%3Aforforever73%20OR%20author%3Achaxu01%20OR%20author%3Alhez%20OR%20author%3AAlekseiNikiforovIBM%20OR%20author%3Anetrunnereve%20OR%20author%3Afairydreaming%20OR%20author%3Aynankani)%20sort%3Aupdated-desc) / [dev stats](https://github.com/ggml-org/llama.cpp-dev) / [lib llama API](https://github.com/ggml-org/llama.cpp/issues/9289) / [llama-server REST API](https://github.com/ggml-org/llama.cpp/issues/9291) +## Description + +The main goal of `llama.cpp` is to enable LLM (and MLLM) inference with minimal setup and state-of-the-art performance on a wide range of hardware - locally and in the cloud. + +The `llama.cpp` project is built on top of the [ggml](https://github.com/ggml-org/ggml) library. + ## Quick start A few options to get `llama.cpp` installed on your machine: @@ -51,50 +57,12 @@ llama serve -hf ggml-org/Qwen3.5-0.8B-GGUF VLM session with llama cli - Built-in web UI against `llama serve` running Qwen 3.6 - Built-in web UI against llama serve + Llama Chat, the built-in chat app, against `llama serve` running Qwen 3.6 + Llama Chat, the built-in chat app, against llama serve -## Description - -The main goal of `llama.cpp` is to enable LLM (and VLM) inference with minimal setup and state-of-the-art performance on -a wide range of hardware - locally and in the cloud. - -- Plain C/C++ implementation without any dependencies -- Apple silicon is a first-class citizen - optimized via ARM NEON, Accelerate and Metal frameworks -- AVX, AVX2, AVX512 and AMX support for x86 architectures -- RVV, ZVFH, ZFH, ZICBOP and ZIHINTPAUSE support for RISC-V architectures -- 1.5-bit, 2-bit, 3-bit, 4-bit, 5-bit, 6-bit, and 8-bit integer quantization for faster inference and reduced memory use -- Custom CUDA kernels for running LLMs on NVIDIA GPUs (support for AMD GPUs via HIP and Moore Threads GPUs via MUSA) -- Vulkan and SYCL backend support -- CPU+GPU hybrid inference to partially accelerate models larger than the total VRAM capacity - -The `llama.cpp` project is build on top of the [ggml](https://github.com/ggml-org/ggml) library. - -## Supported backends - -| Backend | Target devices | -| --- | --- | -| [BLAS](docs/build.md#blas-build) | All | -| [BLIS](docs/backend/BLIS.md) | All | -| [CANN](docs/build.md#cann) | Huawei Ascend NPU | -| [CUDA](docs/build.md#cuda) | Nvidia GPU | -| [HIP](docs/build.md#hip) | AMD GPU | -| [Hexagon](docs/backend/snapdragon/README.md) | Snapdragon | -| [IBM zDNN](docs/backend/zDNN.md) | IBM Z & LinuxONE | -| [MUSA](docs/build.md#musa) | Moore Threads GPU | -| [Metal](docs/build.md#metal-build) | Apple Silicon | -| [OpenCL](docs/backend/OPENCL.md) | Adreno GPU | -| [OpenVINO [In Progress]](docs/backend/OPENVINO.md) | Intel CPUs, GPUs, and NPUs | -| [RPC](https://github.com/ggml-org/llama.cpp/tree/master/tools/rpc) | All | -| [SYCL](docs/backend/SYCL.md) | Intel GPU | -| [VirtGPU](docs/backend/VirtGPU.md) | VirtGPU APIR | -| [Vulkan](docs/build.md#vulkan) | GPU | -| [WebGPU](docs/build.md#webgpu) | All | -| [ZenDNN](docs/build.md#zendnn) | AMD CPU | - ## Documentation #### Tools @@ -102,6 +70,7 @@ The `llama.cpp` project is build on top of the [ggml](https://github.com/ggml-or - [cli](tools/cli/README.md) - [completion](tools/completion/README.md) - [server](tools/server/README.md) +- [Text-to-speech (TTS) models](docs/multimodal/tts.md) - [GBNF grammars](grammars/README.md) #### Development diff --git a/SECURITY.md b/SECURITY.md index bc6ed9d809a1..e781871647d4 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -46,7 +46,7 @@ Only vulnerabilities that fall within these parts of the project are considered - `ggml/**/*` - `gguf-py/**/*` - `tools/server/*`, **excluding** the following topics: - - Web UI + - Llama Chat, the built-in chat app (`ui/apps/chat`) - Features marked as experimental - Features not recommended for use in untrusted environments (e.g., router, MCP) - Bugs that can lead to Denial-of-Service attack diff --git a/ci/run.sh b/ci/run.sh index 1beb54b0759d..cb8918ab9c86 100755 --- a/ci/run.sh +++ b/ci/run.sh @@ -122,6 +122,8 @@ if [ ! -z ${GG_BUILD_VULKAN} ]; then MACOS_RUNNER_CUSTOM_SPIRV_HEADERS_LOCATION="${MACOS_RUNNER_CUSTOM_VULKAN_CMAKE_LOCATION}/SPIRV-Headers/SPIRV-HeadersConfig.cmake" if [[ -f "${MACOS_RUNNER_CUSTOM_SPIRV_HEADERS_LOCATION}" || -h "${MACOS_RUNNER_CUSTOM_SPIRV_HEADERS_LOCATION}" ]]; then CMAKE_EXTRA="${CMAKE_EXTRA} -DSPIRV-Headers_DIR=${MACOS_RUNNER_CUSTOM_VULKAN_CMAKE_LOCATION}/SPIRV-Headers" + # SPIRV-Headers walks up three directories and appends /include, yielding /usr/local/lib/include; the extra vulkan/ level likely breaks its prefix calculation. + CMAKE_EXTRA="${CMAKE_EXTRA} -DGGML_VULKAN_SPIRV_INCLUDE_DIR=/usr/local/include" fi fi diff --git a/common/arg.cpp b/common/arg.cpp index 6bf9355fb0ff..192f70607f1e 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -349,6 +349,14 @@ common_models_handler common_models_handler_init(const common_params & params, l params.speculative.types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH) != params.speculative.types.end(); + const bool spec_type_draft_dflash2 = std::find(params.speculative.types.begin(), + params.speculative.types.end(), + COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2) != params.speculative.types.end(); + + const bool spec_type_draft_lilicorr = std::find(params.speculative.types.begin(), + params.speculative.types.end(), + COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR) != params.speculative.types.end(); + const bool spec_type_draft_eagle3 = std::find(params.speculative.types.begin(), params.speculative.types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3) != params.speculative.types.end(); @@ -373,7 +381,7 @@ common_models_handler common_models_handler_init(const common_params & params, l opts.offline = params.offline; opts.download_mtp = spec_type_draft_mtp; opts.download_eagle3 = spec_type_draft_eagle3; - opts.download_dflash = spec_type_draft_dflash; + opts.download_dflash = spec_type_draft_dflash || spec_type_draft_dflash2 || spec_type_draft_lilicorr; opts.download_dspark = spec_type_draft_dspark; opts.download_mmproj = use_mmproj && !params.no_mmproj && params.mmproj.path.empty() && params.mmproj.url.empty(); @@ -904,6 +912,10 @@ static bool common_params_parse_ex(int argc, char ** argv, common_params_context throw std::invalid_argument("error: --prompt-cache-all not supported in interactive mode yet\n"); } + if (params.sampling.ignore_eos && !common_grammar_value(params.sampling.grammar).empty()) { + throw std::invalid_argument("error: --ignore-eos is not supported with --grammar or --json-schema\n"); + } + const bool skip_model_download = // server will call common_params_handle_models() later, so we skip it here ctx_arg.ex == LLAMA_EXAMPLE_SERVER || @@ -2821,7 +2833,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex const std::regex regex{ R"([,/]+)" }; std::sregex_token_iterator it{ arg_next.begin(), arg_next.end(), regex, -1 }; std::vector split_arg{ it, {} }; - if (split_arg.size() >= llama_max_devices()) { + if (split_arg.size() > llama_max_devices()) { throw std::invalid_argument( string_format("got %zu input configs, but system only has %zu devices", split_arg.size(), llama_max_devices()) ); @@ -2887,7 +2899,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex const std::regex regex{ R"([,/]+)" }; std::sregex_token_iterator it{ arg_next.begin(), arg_next.end(), regex, -1 }; std::vector split_arg{ it, {} }; - if (split_arg.size() >= llama_max_devices()) { + if (split_arg.size() > llama_max_devices()) { throw std::invalid_argument( string_format("got %zu input configs, but system only has %zu devices", split_arg.size(), llama_max_devices()) ); @@ -3408,7 +3420,7 @@ 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 the Web UI 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 - 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; @@ -3477,7 +3489,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex add_opt(common_arg( {"--ui", "--webui"}, {"--no-ui", "--no-webui"}, - string_format("whether to enable the Web UI (default: %s)", params.ui ? "enabled" : "disabled"), + string_format("whether to enable Llama Chat, the built-in chat app (default: %s)", params.ui ? "enabled" : "disabled"), [](common_params & params, bool value) { params.ui = value; } @@ -4494,7 +4506,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex add_opt(common_arg( {"--tts-lang"}, "FNAME", "language (ISO 639-1) for audio generation\n" - "see tts/README.md for per-model usage notes", + "see docs/multimodal/tts.md for per-model usage notes", [](common_params & params, const std::string & value) { params.tts_lang = value; } @@ -4502,7 +4514,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex add_opt(common_arg( {"--tts-voice"}, "VOICE", "voice for audio generation (model-dependent)\n" - "see tts/README.md for per-model usage notes", + "see docs/multimodal/tts.md for per-model usage notes", [](common_params & params, const std::string & value) { params.tts_voice = value; } @@ -4514,6 +4526,14 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.tts_speaker_file = value; } ).set_examples({LLAMA_EXAMPLE_TTS})); + add_opt(common_arg( + {"--tts-speaker-text"}, "TEXT", + "transcript of --tts-speaker-file, for models that need it to clone the voice\n" + "see docs/multimodal/tts.md for per-model usage notes", + [](common_params & params, const std::string & value) { + params.tts_speaker_text = value; + } + ).set_examples({LLAMA_EXAMPLE_TTS})); // // diffusion params diff --git a/common/chat-peg-parser.cpp b/common/chat-peg-parser.cpp index 968cbfa98f6c..56938d5efcd1 100644 --- a/common/chat-peg-parser.cpp +++ b/common/chat-peg-parser.cpp @@ -562,7 +562,8 @@ common_peg_parser common_chat_peg_builder::python_or_json_value() { common_peg_parser common_chat_peg_builder::python_style_tool_calls( const ordered_json & tools, bool parallel_tool_calls, - bool allow_json_literals) { + bool allow_json_literals, + bool allow_undeclared) { if (!tools.is_array() || tools.empty()) { return eps(); } @@ -620,6 +621,18 @@ common_peg_parser common_chat_peg_builder::python_style_tool_calls( tool_choices |= rule("tool-" + std::to_string(i), tool_parser); } + // last, so declared tools win when parsing + if (allow_undeclared) { + auto ident = rule("tool-undeclared-ident", chars("[a-zA-Z_]", 1, 1) + chars("[a-zA-Z0-9_.]", 0, -1)); + auto value = tool_arg_value(allow_json_literals ? python_or_json_value() : python_value()); + auto arg = tool_arg(tool_arg_open(tool_arg_name(ident) + literal("=")) + value + tool_arg_close(eps())); + auto args = optional(arg + zero_or_more("," + space() + arg)); + + tool_choices |= rule("tool-undeclared", tool(tool_open(tool_name(ident) + literal("(")) + + space() + tool_args(args) + space() + tool_close(literal(")")) + )); + } + if (parallel_tool_calls) { return "[" + space() + tool_choices + zero_or_more("," + space() + tool_choices) + space() + "]"; } diff --git a/common/chat-peg-parser.h b/common/chat-peg-parser.h index b827b60b059c..c77ec117b5aa 100644 --- a/common/chat-peg-parser.h +++ b/common/chat-peg-parser.h @@ -161,9 +161,11 @@ class common_chat_peg_builder : public common_peg_parser_builder { // Helper for Python-style function call format: name(arg1="value1", arg2=123) // Used by LFM2 and similar templates + // allow_undeclared: also accept calls to names not in tools (any identifier, any arguments) common_peg_parser python_style_tool_calls(const common_json & tools, bool parallel_tool_calls, - bool allow_json_literals); + bool allow_json_literals, + bool allow_undeclared = false); private: // Python values plus JSON true/false/null. diff --git a/common/chat-tts-norm.cpp b/common/chat-tts-norm.cpp index f84540ff96e0..b828ed9b4e18 100644 --- a/common/chat-tts-norm.cpp +++ b/common/chat-tts-norm.cpp @@ -2,6 +2,7 @@ #include "jinja/runtime.h" #include "jinja/value.h" +#include "json.h" #include #include @@ -857,8 +858,45 @@ static value tts_norm_builtin_sub(const func_args & args) { return mk_val(string(res, text_val.all_parts_are_input())); } -void common_chat_tts_norm_add_builtins(context & ctx) { +bool common_tts_dict_find(const common_tts_dict & dict, const std::string & key, std::string & value) { + const auto it = std::lower_bound(dict.keys.begin(), dict.keys.end(), key); + if (it == dict.keys.end() || *it != key) { + return false; + } + const size_t idx = it - dict.keys.begin(); + if (idx >= dict.values.size()) { + throw std::runtime_error("tts_dict: malformed dictionary, a key has no value"); + } + value = dict.values[idx]; + return true; +} + +void common_chat_tts_norm_add_builtins(context & ctx, std::shared_ptr dicts, common_tts_g2p g2p) { ctx.set_val("tts_norm_scan", mk_val("tts_norm_scan", tts_norm_builtin_scan)); ctx.set_val("tts_norm_sub", mk_val("tts_norm_sub", tts_norm_builtin_sub)); + ctx.set_val("tts_dict", mk_val("tts_dict", [dicts](const func_args & args) -> value { + args.ensure_count(2, 2); + args.ensure_vals(); + const std::string name = args.get_pos(0)->as_string().str(); + const auto it = dicts ? dicts->find(name) : common_tts_dicts::const_iterator(); + if (!dicts || it == dicts->end()) { + throw std::runtime_error("tts_dict: unknown dictionary '" + name + "'"); + } + std::string doc; + if (!common_tts_dict_find(it->second, args.get_pos(1)->as_string().str(), doc)) { + return mk_val(); + } + return value_from_json(common_json::parse(doc), false); + })); + // none when the caller gives no letter-to-sound model, or the model has no pronunciation + ctx.set_val("tts_g2p", mk_val("tts_g2p", [g2p](const func_args & args) -> value { + args.ensure_count(1, 1); + args.ensure_vals(); + const std::string out = g2p ? g2p(args.get_pos(0)->as_string().str()) : std::string(); + if (out.empty()) { + return mk_val(); + } + return mk_val(out); + })); } diff --git a/common/chat-tts-norm.h b/common/chat-tts-norm.h index 14695bb52d99..b96486078602 100644 --- a/common/chat-tts-norm.h +++ b/common/chat-tts-norm.h @@ -1,6 +1,8 @@ #pragma once #include +#include +#include #include #include #include @@ -11,9 +13,10 @@ // it is NOT a regex engine: the semantics are defined by llama.cpp (see docs/tts-norm-patterns.md), so that this // implementation and the python reference (scripts/chat_tts_norm.py) give the same result for every input // -// two functions are exposed to task templates (e.g. "tts") via common_chat_tts_norm_add_builtins(): +// functions exposed to task templates (e.g. "tts") via common_chat_tts_norm_add_builtins(): // tts_norm_scan(text, rules) -> list of segments {rule, text, groups} // tts_norm_sub(text, pattern, repl) -> string +// tts_dict(name, key) -> value of key in a dictionary of the model, or none namespace jinja { struct context; @@ -57,6 +60,22 @@ std::vector common_tts_norm_scan(const std::string & te // repl references: %0 (whole match), %1..%9 (groups), %% (literal percent) std::string common_tts_norm_sub(const std::string & text, const common_tts_norm_pattern & pattern, const std::string & repl); -// add tts_norm_scan() and tts_norm_sub() to the context of a task template +// a dictionary of the model, e.g. a pronunciation lexicon +struct common_tts_dict { + std::vector keys; // sorted by their bytes + std::vector values; // the JSON document of each key +}; + +using common_tts_dicts = std::map; + +// binary search of key in a dictionary; on success, value is set to the JSON document +bool common_tts_dict_find(const common_tts_dict & dict, const std::string & key, std::string & value); + +// pronunciation of a word by a letter-to-sound model, as phonemes separated by spaces (e.g. CMUdict notation) +// empty when there is none; the notation is the one of the model, its "tts" template knows it +using common_tts_g2p = std::function; + +// add tts_norm_scan(), tts_norm_sub(), tts_dict() and tts_g2p() to the context of a task template // they are not jinja global builtins on purpose: chat templates are not affected -void common_chat_tts_norm_add_builtins(jinja::context & ctx); +void common_chat_tts_norm_add_builtins(jinja::context & ctx, std::shared_ptr dicts = nullptr, + common_tts_g2p g2p = nullptr); diff --git a/common/chat.cpp b/common/chat.cpp index da29cd671d4c..de5f1c490303 100644 --- a/common/chat.cpp +++ b/common/chat.cpp @@ -318,6 +318,7 @@ struct common_chat_templates { std::unique_ptr template_default; // always set (defaults to chatml) std::unique_ptr template_tool_use; std::unique_ptr template_tts; // the prompt of a text to speak + std::shared_ptr tts_dicts; // dictionaries of the model for tts_dict(), by name }; common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::string & tool_choice) { @@ -806,10 +807,11 @@ bool common_chat_templates_was_explicit(const struct common_chat_templates * tmp } // renders a task template (e.g. "tts") with the given variables -static std::string common_chat_template_render(const common_chat_template & tmpl, const json & vars) { +static std::string common_chat_template_render(const common_chat_template & tmpl, const json & vars, const std::shared_ptr & tts_dicts, + const common_tts_g2p & g2p = nullptr) { jinja::context ctx(tmpl.source()); - // text normalization helpers: tts_norm_scan() and tts_norm_sub(), see docs/tts-norm-patterns.md - common_chat_tts_norm_add_builtins(ctx); + // text normalization helpers: tts_norm_scan(), tts_norm_sub(), tts_dict() and tts_g2p(), see docs/tts-norm-patterns.md + common_chat_tts_norm_add_builtins(ctx, tts_dicts, g2p); jinja::global_from_json(ctx, vars, false); ctx.set_val("bos_token", jinja::mk_val(tmpl.bos_token())); ctx.set_val("eos_token", jinja::mk_val(tmpl.eos_token())); @@ -827,6 +829,11 @@ static std::string string_lower(std::string s) { return s; } +// VibeVoice-ASR: default system prompt of the template written by the converter +static bool is_vibevoice_asr_template(const std::string & src) { + return src.find("transcribes audio input into text output in JSON format") != std::string::npos; +} + // LFM3-Audio: language code -> name static std::string lfm3_language_name(const std::string & language) { static const std::map names = { @@ -847,7 +854,8 @@ static std::string lfm3_asr_system_prompt(const std::string & language) { return "Perform ASR in " + lfm3_language_name(language) + "."; } -common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language) { +common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language, + double audio_length, const std::string & context) { common_chat_prompt_preset asr_preset; asr_preset.system = ""; asr_preset.user = "Transcribe audio to text"; @@ -861,6 +869,17 @@ common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates asr_preset.system = lfm3_asr_system_prompt(language); asr_preset.user = ""; asr_preset.has_language = true; + } else if (is_vibevoice_asr_template(src)) { + // without the audio length the model does not know where the audio ends and loops + const char * keys = "transcribe it with these keys: Start time, End time, Speaker ID, Content"; + if (context.empty()) { + asr_preset.user = string_format("\nThis is a %.2f seconds audio, please %s", audio_length, keys); + } else { + asr_preset.user = string_format("\nThis is a %.2f seconds audio, with extra info: %s\n\nPlease %s", audio_length, context.c_str(), keys); + asr_preset.has_context = true; + } + asr_preset.media_first = true; + asr_preset.needs_audio_length = true; } } @@ -868,7 +887,7 @@ common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates } std::string common_chat_get_tts_prompt(const common_chat_templates * chat_templates, const std::string & text, - const std::string & language, const std::string & voice) { + const std::string & language, const std::string & voice, const common_tts_g2p & g2p) { if (!chat_templates || !chat_templates->template_tts) { return ""; } @@ -876,7 +895,7 @@ std::string common_chat_get_tts_prompt(const common_chat_templates * chat_templa {"messages", json::array({{{"role", "user"}, {"content", text}}})}, {"language", language}, {"voice", voice}, - }); + }, chat_templates->tts_dicts, g2p); } std::string common_chat_get_speech_system_prompt(const common_chat_templates * chat_templates, @@ -955,18 +974,6 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model * "{%- if false %}"); } - // TODO @aldehir : this is a temporary fix, pending Minja changes - // Ref: https://github.com/ggml-org/llama.cpp/pull/17713#issuecomment-3631342664 - if (default_template_src.find("[TOOL_CALLS]") != std::string::npos - // search for the error message and patch it - && default_template_src.find("if (message['content'] is none or") != std::string::npos) { - string_replace_all(default_template_src, - "{%- if (message['content'] is none or message['content'] == '' or " - "message['content']|length == 0) and (message['tool_calls'] is not defined or " - "message['tool_calls'] is none or message['tool_calls']|length == 0) %}", - "{%- if false %}"); - } - std::string token_bos = bos_token_override; std::string token_eos = eos_token_override; bool add_bos = false; @@ -1019,6 +1026,25 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model * LOG_ERR("%s: failed to parse the tts chat template (ignoring it): %s\n", __func__, e.what()); } } + // dictionaries for tts_dict(), listed by name in tokenizer.tts_dicts + tmpls->tts_dicts = std::make_shared(); + for (int32_t i = 0; i < llama_model_meta_arr_n(model, "tokenizer.tts_dicts"); i++) { + const std::string name = llama_model_meta_arr_str(model, "tokenizer.tts_dicts", i); + const std::string key = "tokenizer.tts_dict." + name + ".keys"; + const std::string val_key = "tokenizer.tts_dict." + name + ".values"; + const int32_t n = llama_model_meta_arr_n(model, key.c_str()); + if (n < 0 || llama_model_meta_arr_n(model, val_key.c_str()) != n) { + LOG_ERR("%s: the tts dictionary '%s' has no value for each of its keys (ignoring it)\n", __func__, name.c_str()); + continue; + } + auto & dict = (*tmpls->tts_dicts)[name]; + dict.keys.reserve(n); + dict.values.reserve(n); + for (int32_t j = 0; j < n; j++) { + dict.keys.emplace_back(llama_model_meta_arr_str(model, key.c_str(), j)); + dict.values.emplace_back(llama_model_meta_arr_str(model, val_key.c_str(), j)); + } + } } return tmpls; } @@ -1439,6 +1465,12 @@ static common_chat_params_init_fn common_chat_template_detect_params_init(const return common_chat_params_init_qwen3_coder; } + // Inkling 1 and 2 + if (is_inkling_template(src)) { + LOG_DBG("Using specialized template: Inkling\n"); + return common_chat_params_init_inkling; + } + return nullptr; } @@ -1971,5 +2003,6 @@ common_json common_chat_templates_get_caps(const common_chat_templates * chat_te : chat_templates->template_default->caps; common_json result = caps.to_map(); result["reasoning_effort_levels"] = caps.reasoning_effort_levels; + result["reasoning_effort_rejected"] = caps.reasoning_effort_rejected; return result; } diff --git a/common/chat.h b/common/chat.h index 304ccf9eca38..43331b16d4a0 100644 --- a/common/chat.h +++ b/common/chat.h @@ -491,15 +491,23 @@ std::optional common_chat_try_specialized_template( struct common_chat_prompt_preset { std::string system; std::string user; - bool has_language = false; // the preset already names the requested language + bool has_language = false; // the preset already names the requested language + bool has_context = false; // the user text already holds the context + bool media_first = false; // the media goes before the user text + bool needs_audio_length = false; // the user text depends on the audio length, call again with it }; -common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language = ""); +// audio_length: in seconds, 0 if unknown +// context: extra info from the user (e.g. names, hotwords), only used by some presets, see has_context +common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language = "", + double audio_length = 0.0, const std::string & context = ""); // prompt of the model's "tts" chat template for the text to speak, empty if the model has none // language and voice are optional, the template defines their defaults +// g2p (optional): the letter-to-sound model of the template's tts_g2p(), e.g. mtmd_gen_audio_g2p() std::string common_chat_get_tts_prompt(const common_chat_templates * chat_templates, const std::string & text, - const std::string & language = "", const std::string & voice = ""); + const std::string & language = "", const std::string & voice = "", + const std::function & g2p = nullptr); // system prompt line for the speech language and voice (e.g. LFM3-Audio), empty if not used std::string common_chat_get_speech_system_prompt(const common_chat_templates * chat_templates, diff --git a/common/common.cpp b/common/common.cpp index 657dcdbf530c..b009d460d697 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1313,6 +1313,11 @@ common_init_result::common_init_result(common_params & params, bool model_only) LOG_INF("%s", "decision model reads the embeddings output, enabling embedding mode\n"); } + // 0 is n_batch + if ((decision_type == COMMON_DECISION_TYPE_LFM3_D1 || decision_type == COMMON_DECISION_TYPE_LFM3_D1_OMNI) && cparams.n_outputs_max != 0) { + cparams.n_outputs_max = std::max(cparams.n_outputs_max, (uint32_t) COMMON_DECISION_LFM3_D1_SET_SIZE); + } + if (llama_model_classifier_free_guidance(model)) { params.kv_unified = true; cparams.kv_unified = true; @@ -2334,6 +2339,9 @@ llama_batch_ext * common_batch::get_sub_batch(int32_t off, int32_t n) { if (t.decision_order != 0) { llama_batch_ext_set_decision_order(res, idx, (llama_decision_order) t.decision_order); } + if (t.decision_group != 0 && !llama_batch_ext_set_decision_group(res, idx, t.decision_group)) { + GGML_ABORT("%s: failed to set the decision group of the entry at index %d\n", __func__, i); + } } return res; diff --git a/common/common.h b/common/common.h index 6043ab34239f..e16bee7c1629 100644 --- a/common/common.h +++ b/common/common.h @@ -174,18 +174,20 @@ enum common_params_sampling_config : uint64_t { }; enum common_speculative_type { - COMMON_SPECULATIVE_TYPE_NONE, // no speculative decoding - COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE, // standalone draft model speculative decoding - COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3, // Eagle3 speculative decoding - COMMON_SPECULATIVE_TYPE_DRAFT_MTP, // Multi-token prediction - COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH, // DFlash speculative decoding - COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK, // DSpark speculative decoding (DFlash + Markov head) - COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE, // simple self-speculative decoding based on n-grams - COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K, // self-speculative decoding with n-gram keys only - COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V, // self-speculative decoding with n-gram keys and 4 m-gram values + COMMON_SPECULATIVE_TYPE_NONE, // no speculative decoding + COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE, // standalone draft model speculative decoding + COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3, // Eagle3 speculative decoding + COMMON_SPECULATIVE_TYPE_DRAFT_MTP, // Multi-token prediction + COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH, // DFlash speculative decoding + COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK, // DSpark speculative decoding (DFlash + Markov head) + COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2, // DFlash2 speculative decoding (DFlash + selector) + COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR, // LiliCorr speculative decoding (DFlash + scorer) + COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE, // simple self-speculative decoding based on n-grams + COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K, // self-speculative decoding with n-gram keys only + COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V, // self-speculative decoding with n-gram keys and 4 m-gram values COMMON_SPECULATIVE_TYPE_NGRAM_MOD, - COMMON_SPECULATIVE_TYPE_NGRAM_CACHE, // self-speculative decoding with 3-level n-gram cache - COMMON_SPECULATIVE_TYPE_COUNT // number of types, unknown type + COMMON_SPECULATIVE_TYPE_NGRAM_CACHE, // self-speculative decoding with 3-level n-gram cache + COMMON_SPECULATIVE_TYPE_COUNT // number of types, unknown type }; // Grammar type enumeration @@ -414,7 +416,12 @@ struct common_params_speculative { uint32_t need_n_rs_seq() const { bool needs_rs_seq = std::any_of(types.begin(), types.end(), [&](auto t) { - return t == COMMON_SPECULATIVE_TYPE_DRAFT_MTP || t == COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3 || t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK; + return t == COMMON_SPECULATIVE_TYPE_DRAFT_MTP || + t == COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3 || + t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || + t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK || + t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2 || + t == COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR; }); return needs_rs_seq ? draft.n_max : 0u; @@ -789,6 +796,7 @@ struct common_params { std::string tts_lang = ""; std::string tts_voice = ""; std::string tts_speaker_file = ""; + std::string tts_speaker_text = ""; bool is_gen_docs = false; // whether we are running inside llama-gen-docs }; @@ -994,6 +1002,9 @@ enum common_decision_type { COMMON_DECISION_TYPE_UNKNOWN, // a decision model of a type that is not supported }; +// lfm3-d1: max questions packed in one prompt +#define COMMON_DECISION_LFM3_D1_SET_SIZE 16 + common_decision_type common_get_decision_type(const struct llama_model * model); // metadata of a GGUF file, read without loading the model @@ -1109,6 +1120,7 @@ struct common_batch { llama_embd state; // non-owning view of the data passed to set_embd_state(), data == NULL if none std::vector seq_ids_extra; // see add_seq() int32_t decision_order = 0; // see llama_batch_ext_set_decision_order() + int32_t decision_group = 0; // see llama_batch_ext_set_decision_group() int32_t embd_row = -1; // see add_embd_row(), -1 if none int32_t state_row = -1; // see set_embd_state_row(), -1 if none }; diff --git a/common/jinja/caps.cpp b/common/jinja/caps.cpp index de7780bdf77c..cf14c71c56d9 100644 --- a/common/jinja/caps.cpp +++ b/common/jinja/caps.cpp @@ -627,9 +627,14 @@ caps caps_get(jinja::program & prog) { // levels sharing a render are aliases and the highest one is kept const auto unknown = render("REASONING_EFFORT_UNKNOWN"); std::vector renders; + std::vector rejected; for (const auto & level : candidates) { const auto rendered = render(level); - if (!rendered || rendered == unknown) { + if (!rendered) { + rejected.push_back(level); + continue; + } + if (rendered == unknown) { continue; } const auto it = std::find(renders.begin(), renders.end(), *rendered); @@ -640,6 +645,11 @@ caps caps_get(jinja::program & prog) { result.reasoning_effort_levels.push_back(level); } } + + // a template that renders no level fails the probe for another reason, so its failures say nothing about the levels + if (!result.reasoning_effort_levels.empty()) { + result.reasoning_effort_rejected = rejected; + } } JJ_DEBUG("%s\n", result.to_string().c_str()); diff --git a/common/jinja/caps.h b/common/jinja/caps.h index 108501e06b7c..f231309e6d1b 100644 --- a/common/jinja/caps.h +++ b/common/jinja/caps.h @@ -23,6 +23,9 @@ struct caps { // reasoning effort levels the template renders distinctly, from lowest to highest std::vector reasoning_effort_levels; + // reasoning effort levels the template raises on + std::vector reasoning_effort_rejected; + // one of the 2 content capabilities must be true bool supports_string_content = true; bool supports_typed_content = false; diff --git a/common/jinja/lexer.cpp b/common/jinja/lexer.cpp index bf2dfacdadd2..8007631534ce 100644 --- a/common/jinja/lexer.cpp +++ b/common/jinja/lexer.cpp @@ -263,41 +263,6 @@ lexer_result lexer::tokenize(const std::string & source) { char ch = src[pos]; - bool is_closing_block = ch == '-' && next_pos_is( {'%', '}'} ); - - // Check for unary operators - if (!is_closing_block && (ch == '-' || ch == '+')) { - start_pos = pos; - token::type last_token_type = tokens.empty() ? token::eof : tokens.back().t; - if (last_token_type == token::text || last_token_type == token::eof) { - throw lexer_exception(std::string("unexpected character: ") + ch, source, pos); - } - switch (last_token_type) { - case token::identifier: - case token::numeric_literal: - case token::string_literal: - case token::close_paren: - case token::close_square_bracket: - // Part of a binary operator - // a - 1, 1 - 1, true - 1, "apple" - 1, (1) - 1, a[1] - 1 - // Continue parsing normally - break; - default: { - // Is part of a unary operator - // (-1), [-1], (1 + -1), not -1, -apple - ++pos; // Consume the operator - - // Check for numbers following the unary operator - std::string num = consume_numeric(); - std::string value = std::string(1, ch) + num; - token::type t = num.empty() ? token::unary_operator : token::numeric_literal; - // JJ_DEBUG("consumed unary operator or numeric literal: '%s'", value.c_str()); - tokens.push_back({t, value, start_pos}); - continue; - } - } - } - // Try to match one of the tokens in the mapping table bool matched = false; for (const auto & [seq, typ] : ordered_mapping_table) { diff --git a/common/jinja/lexer.h b/common/jinja/lexer.h index 3f4ebb62a8d5..3b203c6f1819 100644 --- a/common/jinja/lexer.h +++ b/common/jinja/lexer.h @@ -39,7 +39,6 @@ struct token { multiplicative_binary_operator, // * / % power_operator, // ** comparison_binary_operator, // < > <= >= == != - unary_operator, // ! - + comment, // {# ... #} }; type t; @@ -74,7 +73,6 @@ static std::string type_to_string(token::type t) { case token::multiplicative_binary_operator: return "multiplicative_binary_operator"; case token::power_operator: return "power_operator"; case token::comparison_binary_operator: return "comparison_binary_operator"; - case token::unary_operator: return "unary_operator"; case token::comment: return "comment"; default: return "unknown"; } @@ -141,6 +139,7 @@ struct lexer { {"~", token::additive_binary_operator}, {"**", token::power_operator}, {"*", token::multiplicative_binary_operator}, + {"//", token::multiplicative_binary_operator}, {"/", token::multiplicative_binary_operator}, {"%", token::multiplicative_binary_operator}, // Assignment operator diff --git a/common/jinja/parser.cpp b/common/jinja/parser.cpp index 0841828c454a..4807b69951e7 100644 --- a/common/jinja/parser.cpp +++ b/common/jinja/parser.cpp @@ -482,7 +482,8 @@ class parser { } statement_ptr parse_unary_expression() { - if (is(token::unary_operator)) { + // a sign where an operand is expected is unary: -x, 1 + -x, x if c else -1 + if (is(token::additive_binary_operator) && peek().value != "~") { depth_guard guard(*this); size_t start_pos = current; auto op = next(); diff --git a/common/jinja/runtime.cpp b/common/jinja/runtime.cpp index d60a99d2591e..433707d71ae6 100644 --- a/common/jinja/runtime.cpp +++ b/common/jinja/runtime.cpp @@ -89,21 +89,22 @@ value statement::execute(context & ctx) const { } value identifier::execute_impl(context & ctx) const { - auto it = ctx.get_val(val); - auto builtins = global_builtins(); - if (!it->is_undefined()) { + auto it = ctx.find_val(key); + if (it && !it->is_undefined()) { if (ctx.is_get_stats) { value_t::stats_t::mark_used(it); } JJ_DEBUG("Identifier '%s' found, type = %s", val.c_str(), it->type().c_str()); return it; - } else if (builtins.find(val) != builtins.end()) { + } + const auto & builtins = global_builtins(); + auto builtin = builtins.find(val); + if (builtin != builtins.end()) { JJ_DEBUG("Identifier '%s' found in builtins", val.c_str()); - return mk_val(val, builtins.at(val)); - } else { - JJ_DEBUG("Identifier '%s' not found, returning undefined", val.c_str()); - return mk_val(val); + return mk_val(val, builtin->second); } + JJ_DEBUG("Identifier '%s' not found, returning undefined", val.c_str()); + return mk_val(val); } value object_literal::execute_impl(context & ctx) const { @@ -190,11 +191,30 @@ static value exec_binary_op(context & ctx, const token & op, value left_val, val if (is_float) { return mk_val(res); } else { - return mk_val(static_cast(res)); + return mk_val(float_to_int(res)); } } else if (op.value == "/") { JJ_DEBUG("Division operation: %f / %f", a, b); return mk_val(a / b); + } else if (op.value == "//") { + // python semantics: round toward -inf + if (is_val(left_val) && is_val(right_val)) { + const int64_t x = left_val->as_int(); + const int64_t y = right_val->as_int(); + if (y == 0) { + throw std::runtime_error("integer division by zero"); + } + if (y == -1) { + // INT64_MIN / -1 is UB, wrap around instead + return mk_val((int64_t) (0 - (uint64_t) x)); + } + int64_t q = x / y; + if (x % y != 0 && (x < 0) != (y < 0)) { + q -= 1; + } + return mk_val(q); + } + return mk_val(std::floor(a / b)); } else if (op.value == "%") { double rem = std::fmod(a, b); JJ_DEBUG("Modulo operation: %f %% %f = %f", a, b, rem); @@ -202,7 +222,7 @@ static value exec_binary_op(context & ctx, const token & op, value left_val, val if (is_float) { return mk_val(rem); } else { - return mk_val(static_cast(rem)); + return mk_val(float_to_int(rem)); } } else if (op.value == "<") { JJ_DEBUG("Comparison operation: %f < %f is %d", a, b, a < b); @@ -273,12 +293,17 @@ static value exec_binary_op(context & ctx, const token & op, value left_val, val // String membership if (is_val(left_val) && is_val(right_val)) { // case: "a" in "abc" - bool member = test_is_in(); - if (op.value == "in") { - return mk_val(member); - } else if (op.value == "not in") { - return mk_val(!member); + if (op.value == "in" || op.value == "not in") { + bool member = test_is_in(); + return mk_val(op.value == "in" ? member : !member); } + // case: "a" < "b"; UTF-8 byte order is the same as codepoint order, like python + const std::string a = left_val->as_string().str(); + const std::string b = right_val->as_string().str(); + if (op.value == "<") { return mk_val(a < b); } + if (op.value == ">") { return mk_val(a > b); } + if (op.value == "<=") { return mk_val(a <= b); } + if (op.value == ">=") { return mk_val(a >= b); } } // Value key in object @@ -693,7 +718,7 @@ value set_statement::execute_impl(context & ctx) const { } auto obj_ptr = cast_val(object); JJ_DEBUG("Setting object property '%s' with value type %s", prop_name.c_str(), rhs->type().c_str()); - obj_ptr->insert(prop_name, rhs); + obj_ptr->insert(cached_val(ctx, member->static_property), rhs); } else { throw std::runtime_error("Invalid LHS inside assignment expression: " + assignee->type()); @@ -786,13 +811,14 @@ value call_statement::execute_impl(context & ctx) const { } auto * callee_func = cast_val(callee_val); - context caller_ctx(ctx); // new scope for caller execution + // caller() can be saved and called after this scope ended, it owns a snapshot of the variables + auto caller_ctx = std::make_shared(ctx.snapshot()); - const func_handler func = [this, caller_ctx = std::move(caller_ctx)](const func_args & args) -> value { + const func_handler func = [this, caller_ctx](const func_args & args) -> value { if (args.ctx.macro_depth >= JINJA_RECURSIVE_LIMIT) { throw std::runtime_error("macro calls are nested more than " + std::to_string(JINJA_RECURSIVE_LIMIT) + " levels deep"); } - context block_ctx(caller_ctx); // new scope for block execution + context block_ctx(*caller_ctx); // new scope for block execution block_ctx.macro_depth = args.ctx.macro_depth + 1; bind_parameters("caller", this->caller_args, args, block_ctx); @@ -813,6 +839,19 @@ value call_statement::execute_impl(context & ctx) const { return callee_func->invoke(args); } +member_expression::member_expression(statement_ptr && object, statement_ptr && property, bool computed) : + object(std::move(object)), + property(std::move(property)), + computed(computed) { + chk_type(this->object); + chk_type(this->property); + if (!computed) { + if (const auto * id = cast_stmt(this->property)) { + static_property = id->key; + } + } +} + value member_expression::execute_impl(context & ctx) const { value object = this->object->execute(ctx); @@ -821,14 +860,13 @@ value member_expression::execute_impl(context & ctx) const { // syntax: obj[expr] JJ_DEBUG("Member expression, computing property type %s", this->property->type().c_str()); - int64_t arr_size = 0; - if (is_val(object)) { - arr_size = object->as_array().size(); - } else if (is_val(object)) { - arr_size = object->as_string().length(); - } - if (is_stmt(this->property)) { + int64_t arr_size = 0; + if (is_val(object)) { + arr_size = static_cast(object->as_array().size()); + } else if (is_val(object)) { + arr_size = static_cast(cast_val(object)->val_str.length()); + } auto s = cast_stmt(this->property); value step_val = s->step_expr ? s->step_expr->execute(ctx) : mk_val(1); value start_val = s->start_expr ? s->start_expr->execute(ctx) : (step_val->as_int() < 0 ? mk_val(arr_size - 1) : mk_val(0)); @@ -850,7 +888,7 @@ value member_expression::execute_impl(context & ctx) const { } } else if (is_stmt(this->property)) { // syntax: obj.index - property = mk_val(cast_stmt(this->property)->val); + property = this->property->execute(ctx); if (property->as_int() < 0) { throw std::runtime_error("Static member property cannot be negative"); } @@ -859,8 +897,8 @@ value member_expression::execute_impl(context & ctx) const { if (!is_stmt(this->property)) { throw std::runtime_error("Static member property must be an identifier"); } - property = mk_val(cast_stmt(this->property)->val); - std::string prop = property->as_string().str(); + property = cached_val(ctx, static_property); + const auto & prop = cast_stmt(this->property)->val; JJ_DEBUG("Member expression, object type %s, static property '%s'", object->type().c_str(), prop.c_str()); // behavior of jinja2: obj having prop as a built-in function AND 'prop', as an object key, @@ -868,51 +906,56 @@ value member_expression::execute_impl(context & ctx) const { // while obj['prop'] returns the property value. // example: {"obj": {"items": 123}} -> obj.items is the built-in function, obj['items'] is 123 - value val = try_builtin_func(ctx, prop, object, true); - if (!is_val(val)) { + value val = find_builtin_func(ctx, prop, object); + if (val) { return val; } // else, fallthrough to normal property access below } JJ_DEBUG("Member expression on object type %s, property type %s", object->type().c_str(), property->type().c_str()); - value val = mk_val("object_property"); + value val; if (property->is_undefined()) { JJ_DEBUG("%s", "Member expression property is undefined, returning undefined"); - return val; + return mk_val("object_property"); } ensure_key_type_allowed(property); if (is_val(object)) { JJ_DEBUG("%s", "Accessing property on undefined object, returning undefined"); - return val; + return mk_val("object_property"); } else if (is_val(object)) { - auto key = property->as_string().str(); - val = object->at(property, val); - if (is_val(val)) { - val = try_builtin_func(ctx, key, object, true); + val = object->find(property); + if (!val || is_val(val)) { + val = try_builtin_func(ctx, property->as_string().str(), object, true); } - JJ_DEBUG("Accessed property '%s' value, got type: %s", key.c_str(), val->type().c_str()); + JJ_DEBUG("Accessed property '%s' value, got type: %s", property->as_string().str().c_str(), val->type().c_str()); } else if (is_val(object) || is_val(object)) { if (is_val(property) || is_val(property)) { int64_t index = property->as_int(); JJ_DEBUG("Accessing %s index %d", object->type().c_str(), (int)index); if (is_val(object)) { - auto & arr = object->as_array(); + const auto * arr = cast_val(object); + const auto count = arr->as_array().size(); if (index < 0) { - index += static_cast(arr.size()); - } - if (index >= 0 && index < static_cast(arr.size())) { - val = arr[index]; + // Avoid negating INT64_MIN. + const uint64_t distance = static_cast(-(index + 1)) + 1; + if (distance <= count) { + val = arr->as_array().at(static_cast(count - distance)); + } + } else if (static_cast(index) < count) { + val = arr->as_array().at(static_cast(index)); } } else { // value_string - auto str = object->as_string().str(); - if (index >= 0 && index < static_cast(str.size())) { - val = mk_val(std::string(1, str[index])); + if (index >= 0) { + const auto byte = cast_val(object)->val_str.byte_at(static_cast(index)); + if (byte) { + val = mk_val(std::string(1, *byte)); + } } } @@ -930,7 +973,10 @@ value member_expression::execute_impl(context & ctx) const { val = try_builtin_func(ctx, key, object, true); } - if (ctx.is_get_stats && val && object && property) { + if (!val) { + val = mk_val("object_property"); + } + if (ctx.is_get_stats && object && property) { value_t::stats_t::mark_used(val); value_t::stats_t::mark_used(object); value_t::stats_t::mark_used(property); diff --git a/common/jinja/runtime.h b/common/jinja/runtime.h index 43e1085516da..066c4e0c0ed3 100644 --- a/common/jinja/runtime.h +++ b/common/jinja/runtime.h @@ -81,12 +81,43 @@ struct context { current_time(parent.current_time), is_get_stats(parent.is_get_stats), macro_depth(parent.macro_depth), - // inherit variables (for example, when entering a new scope) - env(mk_val(*parent.env)) {} + // child scope: own variables only, lookups fall back to the parent (which must outlive this scope) + parent(&parent), + env(mk_val()) { + env->has_builtins = false; + } + + context(context &&) = default; + + // copy with all visible variables flattened in, for a scope that can outlive its parents (caller() of a call block) + context snapshot() const { + std::vector chain; + for (const context * c = this; c; c = c->parent) { + chain.push_back(c); + } + context res(*this); + res.parent = nullptr; + for (auto it = chain.rbegin(); it != chain.rend(); ++it) { + for (const auto & kv : (*it)->env->as_ordered_object()) { + res.env->insert(kv.first, kv.second); + } + } + return res; + } + + // returns nullptr if not found + value find_val(const value & key) { + for (const context * c = this; c; c = c->parent) { + if (value v = c->env->find(key)) { + return v; + } + } + return nullptr; + } value get_val(const std::string & name) { - value default_val = mk_val(name); - return env->at(name, default_val); + auto result = find_val(mk_val(name)); + return result ? result : mk_val(name); } void set_val(const std::string & name, const value & val) { @@ -102,9 +133,16 @@ struct context { } private: + const context * parent = nullptr; value_object env; }; +// values cached in the AST are shared across renders, but stats mutate values, so stats mode gets a fresh copy +template +value cached_val(const context & ctx, const value & cached) { + return ctx.is_get_stats ? mk_val(*cast_val(cached)) : cached; +} + // utils for visiting AST nodes static std::vector stmts_to_ptr(const statements & stmts) { std::vector children; @@ -328,11 +366,8 @@ struct member_expression : public expression { statement_ptr property; bool computed; // true if obj[expr] and false if obj.prop - member_expression(statement_ptr && object, statement_ptr && property, bool computed) - : object(std::move(object)), property(std::move(property)), computed(computed) { - chk_type(this->object); - chk_type(this->property); - } + value static_property; // set if property is an identifier, see cached_val() + member_expression(statement_ptr && object, statement_ptr && property, bool computed); std::string type() const override { return "MemberExpression"; } value execute_impl(context & ctx) const override; void visit(context & ctx) const override { @@ -367,7 +402,8 @@ struct call_expression : public expression { */ struct identifier : public expression { std::string val; - explicit identifier(const std::string & val) : val(val) {} + const value key; // lookup key, safe to share across renders as lookups do not touch stats + explicit identifier(const std::string & val) : val(val), key(mk_val(val)) {} std::string type() const override { return "Identifier"; } value execute_impl(context & ctx) const override; }; @@ -376,28 +412,31 @@ struct identifier : public expression { struct integer_literal : public expression { int64_t val; - explicit integer_literal(int64_t val) : val(val) {} + const value constant; // see cached_val() + explicit integer_literal(int64_t val) : val(val), constant(mk_val(val)) {} std::string type() const override { return "IntegerLiteral"; } - value execute_impl(context &) const override { - return mk_val(val); + value execute_impl(context & ctx) const override { + return cached_val(ctx, constant); } }; struct float_literal : public expression { double val; - explicit float_literal(double val) : val(val) {} + const value constant; // see cached_val() + explicit float_literal(double val) : val(val), constant(mk_val(val)) {} std::string type() const override { return "FloatLiteral"; } - value execute_impl(context &) const override { - return mk_val(val); + value execute_impl(context & ctx) const override { + return cached_val(ctx, constant); } }; struct string_literal : public expression { std::string val; - explicit string_literal(const std::string & val) : val(val) {} + const value constant; // see cached_val() + explicit string_literal(const std::string & val) : val(val), constant(mk_val(val)) {} std::string type() const override { return "StringLiteral"; } - value execute_impl(context &) const override { - return mk_val(val); + value execute_impl(context & ctx) const override { + return cached_val(ctx, constant); } }; @@ -748,7 +787,7 @@ static void gather_string_parts_recursive(const value & val, value_string & part } else if (is_val(val) && depth >= JINJA_RECURSIVE_LIMIT) { throw std::runtime_error("value is nested more than " + std::to_string(JINJA_RECURSIVE_LIMIT) + " levels deep"); } else if (is_val(val)) { - auto items = cast_val(val)->as_array(); + const auto & items = cast_val(val)->as_array(); for (const auto & item : items) { gather_string_parts_recursive(item, parts, depth + 1); } diff --git a/common/jinja/string.cpp b/common/jinja/string.cpp index bde679e4e9df..22189fa6f47c 100644 --- a/common/jinja/string.cpp +++ b/common/jinja/string.cpp @@ -43,14 +43,59 @@ void string::mark_input() { } std::string string::str() const { - if (parts.size() == 1) { - return parts[0].val; + std::string result; + result.reserve(length()); + for (const auto & part : parts) { + result += part.val; + } + return result; +} + +bool string::empty() const { + for (const auto & part : parts) { + if (!part.val.empty()) { + return false; + } } - std::ostringstream oss; + return true; +} + +std::optional string::byte_at(size_t index) const { for (const auto & part : parts) { - oss << part.val; + if (index < part.val.size()) { + return part.val[index]; + } + index -= part.val.size(); + } + return {}; +} + +bool string::equals(const string & other) const { + size_t part = 0, offset = 0; + for (const auto & left : parts) { + std::string_view text(left.val); + while (!text.empty()) { + while (part < other.parts.size() && offset == other.parts[part].val.size()) { + ++part; + offset = 0; + } + if (part == other.parts.size()) { + return false; + } + const auto & right = other.parts[part].val; + const auto count = std::min(text.size(), right.size() - offset); + if (text.substr(0, count) != std::string_view(right).substr(offset, count)) { + return false; + } + text.remove_prefix(count); + offset += count; + } + } + while (part < other.parts.size() && offset == other.parts[part].val.size()) { + ++part; + offset = 0; } - return oss.str(); + return part == other.parts.size(); } size_t string::length() const { diff --git a/common/jinja/string.h b/common/jinja/string.h index 669afb8f1da0..119ad11c2b0e 100644 --- a/common/jinja/string.h +++ b/common/jinja/string.h @@ -39,6 +39,9 @@ struct string { std::string str() const; size_t length() const; + bool empty() const; + bool equals(const string & other) const; + std::optional byte_at(size_t index) const; void hash_update(hasher & hash) const noexcept; bool all_parts_are_input() const; bool is_uppercase() const; diff --git a/common/jinja/value.cpp b/common/jinja/value.cpp index 333241d7a9e7..9692d7cab2f9 100644 --- a/common/jinja/value.cpp +++ b/common/jinja/value.cpp @@ -276,19 +276,17 @@ static value tojson(const func_args & args) { if (args.ctx.is_get_stats) { // mark as used (recursively) for stats auto val_input = args.get_pos(0); - value_t::stats_t::mark_used(const_cast(val_input), true); + value_t::stats_t::mark_used(val_input, true); } if (is_val(val_indent)) { indent = static_cast(val_indent->as_int()); } - if (val_sort->as_bool()) { // undefined == false - throw not_implemented_exception("tojson sort_keys=true not implemented"); - } + const bool sort_keys = val_sort->as_bool(); // undefined == false const bool ensure_ascii = val_ascii->as_bool(); // undefined == false auto separators = (is_val(val_separators) ? val_separators : mk_val())->as_array(); std::string item_sep = separators.size() > 0 ? separators[0]->as_string().str() : (indent < 0 ? ", " : ","); std::string key_sep = separators.size() > 1 ? separators[1]->as_string().str() : ": "; - std::string json_str = value_to_json(args.get_pos(0), indent, item_sep, key_sep); + std::string json_str = value_to_json(args.get_pos(0), indent, item_sep, key_sep, sort_keys); if (ensure_ascii) { json_str = json_ensure_ascii_preserving_format(json_str); } @@ -507,7 +505,12 @@ const func_builtins & global_builtins() { }}, {"test_is_divisibleby", [](const func_args & args) -> value { args.ensure_vals(); - bool res = args.get_pos(0)->val_int % args.get_pos(1)->val_int == 0; + const int64_t a = args.get_pos(0)->as_int(); + const int64_t b = args.get_pos(1)->as_int(); + if (b == 0) { + throw std::runtime_error("divisibleby: division by zero"); + } + bool res = b == -1 || a % b == 0; // avoid INT64_MIN % -1 overflow return mk_val(res); }}, {"test_is_string", test_type_fn}, @@ -519,11 +522,11 @@ const func_builtins & global_builtins() { {"test_is_mapping", test_type_fn}, {"test_is_lower", [](const func_args & args) -> value { args.ensure_vals(); - return mk_val(args.get_pos(0)->val_str.is_lowercase()); + return mk_val(cast_val(args.get_pos(0))->val_str.is_lowercase()); }}, {"test_is_upper", [](const func_args & args) -> value { args.ensure_vals(); - return mk_val(args.get_pos(0)->val_str.is_uppercase()); + return mk_val(cast_val(args.get_pos(0))->val_str.is_uppercase()); }}, {"test_is_none", test_type_fn}, {"test_is_defined", [](const func_args & args) -> value { @@ -571,7 +574,7 @@ const func_builtins & global_builtins() { {"test_is_test", [](const func_args & args) -> value { args.ensure_vals(); auto & builtins = global_builtins(); - std::string test_name = args.get_pos(0)->val_str.str(); + std::string test_name = cast_val(args.get_pos(0))->val_str.str(); auto it = builtins.find("test_is_" + test_name); bool res = it != builtins.end(); return mk_val(res); @@ -613,18 +616,26 @@ const func_builtins & global_builtins() { return builtins; } -value try_builtin_func(context & ctx, const std::string & name, value & input, bool undef_on_missing) { +value find_builtin_func(context & ctx, const std::string & name, value & input) { JJ_DEBUG("Trying built-in function '%s' for type %s", name.c_str(), input->type().c_str()); if (ctx.is_get_stats) { value_t::stats_t::mark_used(input); input->stats.ops.insert(name); } - auto builtins = input->get_builtins(); + const auto & builtins = input->get_builtins(); auto it = builtins.find(name); if (it != builtins.end()) { JJ_DEBUG("Binding built-in '%s'", name.c_str()); return mk_val(name, it->second, input); } + return nullptr; +} + +value try_builtin_func(context & ctx, const std::string & name, value & input, bool undef_on_missing) { + value func = find_builtin_func(ctx, name, input); + if (func) { + return func; + } if (undef_on_missing) { return mk_val(name); } @@ -700,7 +711,7 @@ const func_builtins & value_float_t::get_builtins() const { }}, {"int", [](const func_args & args) -> value { args.ensure_vals(); - int64_t val = static_cast(args.get_pos(0)->as_float()); + int64_t val = float_to_int(args.get_pos(0)->as_float()); return mk_val(val); }}, {"float", [](const func_args & args) -> value { @@ -831,7 +842,7 @@ const func_builtins & value_string_t::get_builtins() const { --maxsplit; } auto res = mk_val(str); - res->val_str.mark_input_based_on(args.get_pos(0)->val_str); + res->val_str.mark_input_based_on(cast_val(args.get_pos(0))->val_str); result->push_back(std::move(res)); return result; }}, @@ -858,7 +869,7 @@ const func_builtins & value_string_t::get_builtins() const { --maxsplit; } auto res = mk_val(str); - res->val_str.mark_input_based_on(args.get_pos(0)->val_str); + res->val_str.mark_input_based_on(cast_val(args.get_pos(0))->val_str); result->push_back(std::move(res)); result->reverse(); return result; @@ -891,7 +902,7 @@ const func_builtins & value_string_t::get_builtins() const { } } auto res = mk_val(str); - res->val_str.mark_input_based_on(args.get_pos(0)->val_str); + res->val_str.mark_input_based_on(cast_val(args.get_pos(0))->val_str); return res; }}, {"format", [](const func_args & args) -> value { @@ -1088,8 +1099,28 @@ const func_builtins & value_bool_t::get_builtins() const { return builtins; } -[[noreturn]] static value array_sum_not_implemented(const func_args &) { - throw not_implemented_exception("Array sum builtin not implemented"); +static value array_sum(const func_args & args) { + args.ensure_kwargs({"attribute", "start"}); + args.ensure_count(1, 3); + args.ensure_vals(); + value undef = mk_val(); + value attribute = args.get_kwarg_or_pos("attribute", 1); + value start = args.get_kwarg_or_pos("start", 2); + // same as the + operator: compute in double, int result if all operands are int + bool is_float = is_val(start); + double sum = start->is_undefined() ? 0.0 : start->as_float(); + for (const auto & item : args.get_pos(0)->as_array()) { + value v = attribute->is_undefined() ? item : get_attribute(item, attribute, undef); + if (v->is_undefined() && !attribute->is_undefined()) { + throw raised_exception("sum: " + item->type() + " has no attribute '" + attribute->as_string().str() + "'"); + } + if (!is_val(v) && !is_val(v)) { + throw raised_exception("sum: unsupported operand type " + v->type()); + } + is_float = is_float || is_val(v); + sum += v->as_float(); + } + return is_float ? value(mk_val(sum)) : value(mk_val(float_to_int(sum))); } const func_builtins & value_array_t::get_builtins() const { @@ -1158,7 +1189,7 @@ const func_builtins & value_array_t::get_builtins() const { {"select", select_or_reject}, {"rejectattr", select_or_reject}, {"reject", select_or_reject}, - {"sum", array_sum_not_implemented}, + {"sum", array_sum}, {"join", [](const func_args & args) -> value { args.ensure_kwargs({"d", "attribute"}); args.ensure_count(1, 3); @@ -1191,7 +1222,7 @@ const func_builtins & value_array_t::get_builtins() const { if (args.ctx.is_get_stats) { // mark as used (recursively) for stats auto val_input = args.get_pos(0); - value_t::stats_t::mark_used(const_cast(val_input), true); + value_t::stats_t::mark_used(val_input, true); } return mk_val(args.get_pos(0)->as_string()); }}, @@ -1439,7 +1470,7 @@ const func_builtins & value_object_t::get_builtins() const { if (args.ctx.is_get_stats) { // mark as used (recursively) for stats auto val_input = args.get_pos(0); - value_t::stats_t::mark_used(const_cast(val_input), true); + value_t::stats_t::mark_used(val_input, true); } return mk_val(args.get_pos(0)->as_string()); }}, @@ -1643,6 +1674,11 @@ bool value_compare(const value & a, const value & b, value_compare_op op) { return result; } +template<> +value value_from_json(const common_json & json_val, bool mark_input) { + return from_json(json_val, mark_input); +} + template<> void global_from_json(context & ctx, const common_json & json_obj, bool mark_input) { // printf("global_from_json: %s\n" , json_obj.dump(2).c_str()); @@ -1728,7 +1764,7 @@ static std::string float_json(double val) { // recursively convert value to JSON string // TODO: avoid circular references -static void value_to_json_internal(std::ostringstream & oss, const value & val, int curr_lvl, int indent, const std::string_view item_sep, const std::string_view key_sep) { +static void value_to_json_internal(std::ostringstream & oss, const value & val, int curr_lvl, int indent, const std::string_view item_sep, const std::string_view key_sep, bool sort_keys) { auto indent_str = [indent, curr_lvl]() -> std::string { return (indent > 0) ? std::string(curr_lvl * indent, ' ') : ""; }; @@ -1775,7 +1811,7 @@ static void value_to_json_internal(std::ostringstream & oss, const value & val, oss << newline(); for (size_t i = 0; i < arr.size(); ++i) { oss << indent_str() << (indent > 0 ? std::string(indent, ' ') : ""); - value_to_json_internal(oss, arr[i], curr_lvl + 1, indent, item_sep, key_sep); + value_to_json_internal(oss, arr[i], curr_lvl + 1, indent, item_sep, key_sep, sort_keys); if (i < arr.size() - 1) { oss << item_sep; } @@ -1786,17 +1822,25 @@ static void value_to_json_internal(std::ostringstream & oss, const value & val, oss << "]"; } else if (is_val(val)) { const auto & obj = val->as_ordered_object(); // IMPORTANT: need to keep exact order + std::vector> items; + items.reserve(obj.size()); + for (const auto & pair : obj) { + items.emplace_back(is_val(pair.first) ? float_json(pair.first->as_float()) : pair.first->as_string().str(), pair.second); + } + if (sort_keys) { + // same order as python json.dumps(sort_keys=True): utf-8 byte order is code point order + std::stable_sort(items.begin(), items.end(), [](const auto & a, const auto & b) { return a.first < b.first; }); + } oss << "{"; - if (!obj.empty()) { + if (!items.empty()) { oss << newline(); size_t i = 0; - for (const auto & pair : obj) { + for (const auto & [key, item] : items) { oss << indent_str() << (indent > 0 ? std::string(indent, ' ') : ""); - const std::string key = is_val(pair.first) ? float_json(pair.first->as_float()) : pair.first->as_string().str(); - value_to_json_internal(oss, mk_val(key), curr_lvl + 1, indent, item_sep, key_sep); + value_to_json_internal(oss, mk_val(key), curr_lvl + 1, indent, item_sep, key_sep, sort_keys); oss << key_sep; - value_to_json_internal(oss, pair.second, curr_lvl + 1, indent, item_sep, key_sep); - if (i < obj.size() - 1) { + value_to_json_internal(oss, item, curr_lvl + 1, indent, item_sep, key_sep, sort_keys); + if (i < items.size() - 1) { oss << item_sep; } oss << newline(); @@ -1810,9 +1854,9 @@ static void value_to_json_internal(std::ostringstream & oss, const value & val, } } -std::string value_to_json(const value & val, int indent, const std::string_view item_sep, const std::string_view key_sep) { +std::string value_to_json(const value & val, int indent, const std::string_view item_sep, const std::string_view key_sep, bool sort_keys) { std::ostringstream oss; - value_to_json_internal(oss, val, 0, indent, item_sep, key_sep); + value_to_json_internal(oss, val, 0, indent, item_sep, key_sep, sort_keys); JJ_DEBUG("value_to_json: result=%s", oss.str().c_str()); return oss.str(); } @@ -1833,18 +1877,18 @@ std::string value_to_string_repr(const value & val) { } // stats utility -void value_t::stats_t::mark_used(value & val, bool deep, int depth) { +void value_t::stats_t::mark_used(const value & val, bool deep, int depth) { val->stats.used = true; if (deep && (is_val(val) || is_val(val)) && depth >= JINJA_RECURSIVE_LIMIT) { throw std::runtime_error("value is nested more than " + std::to_string(JINJA_RECURSIVE_LIMIT) + " levels deep"); } if (deep) { if (is_val(val)) { - for (auto & item : val->val_arr) { + for (auto & item : val->as_array()) { mark_used(item, deep, depth + 1); } } else if (is_val(val)) { - for (auto & pair : val->val_obj) { + for (auto & pair : val->as_ordered_object()) { mark_used(pair.first, deep, depth + 1); mark_used(pair.second, deep, depth + 1); } diff --git a/common/jinja/value.h b/common/jinja/value.h index 8fdff884edee..6843bf57a7e0 100644 --- a/common/jinja/value.h +++ b/common/jinja/value.h @@ -21,6 +21,20 @@ namespace jinja { struct value_t; using value = std::shared_ptr; +enum class value_kind { + INTEGER, + REAL, + STRING, + BOOLEAN, + ARRAY, + TUPLE, + OBJECT, + NONE, + UNDEFINED, + FUNCTION, + KEYWORD +}; +bool has_value_kind(const value_t * val, value_kind kind); // Helper to check the type of a value template @@ -34,12 +48,12 @@ struct extract_pointee> { template bool is_val(const value & ptr) { using PointeeType = typename extract_pointee::type; - return dynamic_cast(ptr.get()) != nullptr; + return has_value_kind(ptr.get(), PointeeType::kind_id); } template bool is_val(const value_t * ptr) { using PointeeType = typename extract_pointee::type; - return dynamic_cast(ptr) != nullptr; + return has_value_kind(ptr, PointeeType::kind_id); } template std::shared_ptr::type> mk_val(Args&&... args) { @@ -49,12 +63,12 @@ std::shared_ptr::type> mk_val(Args&&... args) { template const typename extract_pointee::type * cast_val(const value & ptr) { using PointeeType = typename extract_pointee::type; - return dynamic_cast(ptr.get()); + return is_val(ptr) ? static_cast(ptr.get()) : nullptr; } template typename extract_pointee::type * cast_val(value & ptr) { using PointeeType = typename extract_pointee::type; - return dynamic_cast(ptr.get()); + return is_val(ptr) ? static_cast(ptr.get()) : nullptr; } // End Helper @@ -91,6 +105,10 @@ struct context; // forward declaration template void global_from_json(context & ctx, const T_JSON & json_obj, bool mark_input); +// convert a single JSON value, same rules as global_from_json() +template +value value_from_json(const T_JSON & json_val, bool mark_input); + // // base value type // @@ -105,14 +123,7 @@ enum value_compare_op { eq, ge, gt, lt, ne }; bool value_compare(const value & a, const value & b, value_compare_op op); struct value_t { - int64_t val_int; - double val_flt; - string val_str; - - std::vector val_arr; - std::vector> val_obj; - - func_handler val_func; + const value_kind kind; // only used if ctx.is_get_stats = true struct stats_t { @@ -120,10 +131,10 @@ struct value_t { // ops can be builtin calls or operators: "array_access", "object_access" std::set ops; // utility to recursively mark value and its children as used - static void mark_used(value & val, bool deep = false, int depth = 0); + static void mark_used(const value & val, bool deep = false, int depth = 0); } stats; - value_t() = default; + explicit value_t(value_kind kind) : kind(kind) {} value_t(const value_t &) = default; virtual ~value_t() = default; @@ -141,6 +152,10 @@ struct value_t { virtual bool is_undefined() const { return false; } virtual const func_builtins & get_builtins() const { throw_type_error("has no builtins"); } + virtual value find(const value & key) { + value missing; + return at(key, missing); + } virtual bool has_key(const value &) { throw_type_error("is not an object value"); } virtual void insert(const value & /* key */, const value & /* val */) { throw_type_error("is not an object value"); } virtual value & at(const value & /* key */, value & /* default_val */) { throw_type_error("is not an object value"); } @@ -172,15 +187,23 @@ struct value_t { virtual bool nonequal(const value_t & other) const { return !equivalent(other); } }; +inline bool has_value_kind(const value_t * val, value_kind kind) { + return val && (val->kind == kind || + (kind == value_kind::ARRAY && (val->kind == value_kind::TUPLE))); +} + // // utils // const func_builtins & global_builtins(); +// returns nullptr if input has no built-in named `name` +value find_builtin_func(context & ctx, const std::string & name, value & input); +// returns value_undefined(name) if not found and undef_on_missing is set, throws otherwise value try_builtin_func(context & ctx, const std::string & name, value & input, bool undef_on_missing = false); value apply_filter_by_name(context & ctx, std::string filter_id, value input, const func_args & args); -std::string value_to_json(const value & val, int indent = -1, const std::string_view item_sep = ", ", const std::string_view key_sep = ": "); +std::string value_to_json(const value & val, int indent = -1, const std::string_view item_sep = ", ", const std::string_view key_sep = ": ", bool sort_keys = false); // Note: only used for debugging purposes std::string value_to_string_repr(const value & val); @@ -214,11 +237,28 @@ struct value_equality { // primitive value types // +// double to int64, saturating and with nan as 0; a plain cast is undefined outside the int64 range +inline int64_t float_to_int(double v) { + if (std::isnan(v)) { + return 0; + } + if (v >= 9223372036854775808.0) { + return INT64_MAX; + } + if (v <= -9223372036854775808.0) { + return INT64_MIN; + } + return static_cast(v); +} + struct value_int_t : public value_t { - value_int_t(int64_t v) { + static constexpr auto kind_id = value_kind::INTEGER; + int64_t val_int; + double val_flt; + value_int_t(int64_t v) : value_t(kind_id) { val_int = v; val_flt = static_cast(v); - if (static_cast(val_flt) != v) { + if (float_to_int(val_flt) != v) { val_flt = v < 0 ? -INFINITY : INFINITY; } } @@ -239,21 +279,22 @@ struct value_int_t : public value_t { } protected: virtual bool equivalent(const value_t & other) const override { - return other.is_numeric() && val_int == other.val_int && val_flt == other.val_flt; + return other.is_numeric() && val_int == other.as_int() && val_flt == other.as_float(); } virtual bool nonequal(const value_t & other) const override { - return !(typeid(*this) == typeid(other) && val_int == other.val_int); + return !(kind == other.kind && val_int == other.as_int()); } }; using value_int = std::shared_ptr; struct value_float_t : public value_t { - value val; - value_float_t(double v) { + static constexpr auto kind_id = value_kind::REAL; + int64_t val_int; + double val_flt; + value_float_t(double v) : value_t(kind_id) { val_flt = v; - val_int = std::isfinite(v) ? static_cast(v) : 0; - val = mk_val(val_int); + val_int = std::isfinite(v) ? float_to_int(v) : 0; } virtual std::string type() const override { return "Float"; } virtual double as_float() const override { return val_flt; } @@ -272,7 +313,7 @@ struct value_float_t : public value_t { virtual bool is_hashable() const override { return true; } virtual hasher unique_hash() const noexcept override { if (static_cast(val_int) == val_flt) { - return val->unique_hash(); + return value_int_t(val_int).unique_hash(); } else { return hasher(typeid(*this)) .update(&val_int, sizeof(val_int)) @@ -281,19 +322,22 @@ struct value_float_t : public value_t { } protected: virtual bool equivalent(const value_t & other) const override { - return other.is_numeric() && val_int == other.val_int && val_flt == other.val_flt; + return other.is_numeric() && val_int == other.as_int() && val_flt == other.as_float(); } virtual bool nonequal(const value_t & other) const override { - return !(typeid(*this) == typeid(other) && val_flt == other.val_flt); + return !(kind == other.kind && val_flt == other.as_float()); } }; using value_float = std::shared_ptr; struct value_string_t : public value_t { - value_string_t() { val_str = string(); } - value_string_t(const std::string & v) { val_str = string(v); } - value_string_t(const string & v) { val_str = v; } + static constexpr auto kind_id = value_kind::STRING; + string val_str; + value_string_t() : value_t(kind_id) {} + value_string_t(const std::string & v) : value_t(kind_id), val_str(v) {} + value_string_t(const string & v) : value_t(kind_id), val_str(v) {} + value_string_t(string && v) : value_t(kind_id), val_str(std::move(v)) {} virtual std::string type() const override { return "String"; } virtual string as_string() const override { return val_str; } virtual std::string as_repr() const override { @@ -304,7 +348,7 @@ struct value_string_t : public value_t { return ss.str(); } virtual bool as_bool() const override { - return val_str.length() > 0; + return !val_str.empty(); } virtual const func_builtins & get_builtins() const override; virtual bool is_hashable() const override { return true; } @@ -320,51 +364,50 @@ struct value_string_t : public value_t { } protected: virtual bool equivalent(const value_t & other) const override { - return typeid(*this) == typeid(other) && val_str.str() == other.val_str.str(); + return kind == other.kind && val_str.equals(static_cast(other).val_str); } }; using value_string = std::shared_ptr; struct value_bool_t : public value_t { - value val; - value_bool_t(bool v) { + static constexpr auto kind_id = value_kind::BOOLEAN; + int64_t val_int; + double val_flt; + value_bool_t(bool v) : value_t(kind_id) { val_int = static_cast(v); val_flt = static_cast(v); - val = mk_val(val_int); } virtual std::string type() const override { return "Boolean"; } virtual int64_t as_int() const override { return val_int; } + virtual double as_float() const override { return val_flt; } virtual bool as_bool() const override { return val_int; } virtual string as_string() const override { return std::string(val_int ? "True" : "False"); } virtual const func_builtins & get_builtins() const override; virtual bool is_numeric() const override { return true; } virtual bool is_hashable() const override { return true; } virtual hasher unique_hash() const noexcept override { - return val->unique_hash(); + return value_int_t(val_int).unique_hash(); } protected: virtual bool equivalent(const value_t & other) const override { - return other.is_numeric() && val_int == other.val_int && val_flt == other.val_flt; + return other.is_numeric() && val_int == other.as_int() && val_flt == other.as_float(); } virtual bool nonequal(const value_t & other) const override { - return !(typeid(*this) == typeid(other) && val_int == other.val_int); + return !(kind == other.kind && val_int == other.as_int()); } }; using value_bool = std::shared_ptr; struct value_array_t : public value_t { - value_array_t() = default; - value_array_t(value & v) { - val_arr = v->val_arr; - } - value_array_t(std::vector && arr) { - val_arr = arr; - } - value_array_t(const std::vector & arr) { - val_arr = arr; - } + static constexpr auto kind_id = value_kind::ARRAY; + std::vector val_arr; + + value_array_t() : value_t(kind_id) {} + value_array_t(value & v) : value_t(kind_id), val_arr(v->as_array()) {} + value_array_t(std::vector && arr) : value_t(kind_id), val_arr(std::move(arr)) {} + value_array_t(const std::vector & arr) : value_t(kind_id), val_arr(arr) {} void reverse() { if (is_immutable()) { throw std::runtime_error("Attempting to modify immutable type"); @@ -462,24 +505,27 @@ struct value_array_t : public value_t { return hash; } protected: + explicit value_array_t(value_kind kind) : value_t(kind) {} + virtual bool equivalent(const value_t & other) const override { - return typeid(*this) == typeid(other) && is_hashable() && other.is_hashable() && std::equal(val_arr.begin(), val_arr.end(), other.val_arr.begin(), other.val_arr.end(), value_equivalence()); + return kind == other.kind && is_hashable() && other.is_hashable() && std::equal(val_arr.begin(), val_arr.end(), other.as_array().begin(), other.as_array().end(), value_equivalence()); } }; using value_array = std::shared_ptr; struct value_tuple_t : public value_array_t { - value_tuple_t(value & v) { - val_arr = v->val_arr; + static constexpr auto kind_id = value_kind::TUPLE; + value_tuple_t(value & v) : value_array_t(kind_id) { + val_arr = v->as_array(); } - value_tuple_t(std::vector && arr) { - val_arr = arr; + value_tuple_t(std::vector && arr) : value_array_t(kind_id) { + val_arr = std::move(arr); } - value_tuple_t(const std::vector & arr) { + value_tuple_t(const std::vector & arr) : value_array_t(kind_id) { val_arr = arr; } - value_tuple_t(const std::pair & pair) { + value_tuple_t(const std::pair & pair) : value_array_t(kind_id) { val_arr.push_back(pair.first); val_arr.push_back(pair.second); } @@ -490,21 +536,23 @@ using value_tuple = std::shared_ptr; struct value_object_t : public value_t { - std::unordered_map unordered; + static constexpr auto kind_id = value_kind::OBJECT; + std::vector> val_obj; + std::unordered_map key_index; // key -> index in val_obj bool has_builtins = true; // context and loop objects do not have builtins - value_object_t() = default; - value_object_t(value & v) { - val_obj = v->val_obj; - for (const auto & pair : val_obj) { - unordered[pair.first] = pair.second; + value_object_t() : value_t(kind_id) {} + value_object_t(value & v) : value_t(kind_id) { + val_obj = v->as_ordered_object(); + for (size_t i = 0; i < val_obj.size(); i++) { + key_index[val_obj[i].first] = i; } } - value_object_t(const std::map & obj) { + value_object_t(const std::map & obj) : value_t(kind_id) { for (const auto & pair : obj) { insert(pair.first, pair.second); } } - value_object_t(const std::vector> & obj) { + value_object_t(const std::vector> & obj) : value_t(kind_id) { for (const auto & pair : obj) { insert(pair.first, pair.second); } @@ -527,45 +575,40 @@ struct value_object_t : public value_t { return ss.str(); } virtual bool as_bool() const override { - return !unordered.empty(); + return !val_obj.empty(); } virtual bool has_key(const value & key) override { if (!key->is_immutable() || !key->is_hashable()) { throw std::runtime_error("Object key of unhashable type: " + key->type()); } - return unordered.find(key) != unordered.end(); + return key_index.find(key) != key_index.end(); } virtual void insert(const value & key, const value & val) override { - bool replaced = false; if (is_immutable()) { throw std::runtime_error("Attempting to modify immutable type"); } - if (has_key(key)) { - // if key exists, replace value in ordered list instead of appending - for (auto & pair : val_obj) { - if (*(pair.first) == *key) { - pair.second = val; - replaced = true; - break; - } - } - } - unordered[key] = val; - if (!replaced) { + if (!key->is_immutable() || !key->is_hashable()) { + throw std::runtime_error("Object key of unhashable type: " + key->type()); + } + const auto entry = key_index.try_emplace(key, val_obj.size()); + if (entry.second) { val_obj.push_back({key, val}); + } else { + val_obj[entry.first->second].second = val; } } virtual value & at(const value & key, value & default_val) override { - if (!has_key(key)) { - return default_val; + if (!key->is_immutable() || !key->is_hashable()) { + throw std::runtime_error("Object key of unhashable type: " + key->type()); } - return unordered.at(key); + const auto found = key_index.find(key); + return found == key_index.end() ? default_val : val_obj[found->second].second; } virtual value & at(const value & key) override { if (!has_key(key)) { throw std::runtime_error("Key '" + key->as_string().str() + "' not found in value of type " + type()); } - return unordered.at(key); + return val_obj[key_index.at(key)].second; } virtual value & at(const std::string & key, value & default_val) override { value key_val = mk_val(key); @@ -599,7 +642,7 @@ struct value_object_t : public value_t { } protected: virtual bool equivalent(const value_t & other) const override { - return typeid(*this) == typeid(other) && is_hashable() && other.is_hashable() && std::equal(val_obj.begin(), val_obj.end(), other.val_obj.begin(), other.val_obj.end(), value_equivalence()); + return kind == other.kind && is_hashable() && other.is_hashable() && std::equal(val_obj.begin(), val_obj.end(), other.as_ordered_object().begin(), other.as_ordered_object().end(), value_equivalence()); } }; using value_object = std::shared_ptr; @@ -609,6 +652,8 @@ using value_object = std::shared_ptr; // struct value_none_t : public value_t { + static constexpr auto kind_id = value_kind::NONE; + value_none_t() : value_t(kind_id) {} virtual std::string type() const override { return "None"; } virtual bool is_none() const override { return true; } virtual bool as_bool() const override { return false; } @@ -621,14 +666,15 @@ struct value_none_t : public value_t { } protected: virtual bool equivalent(const value_t & other) const override { - return typeid(*this) == typeid(other); + return kind == other.kind; } }; using value_none = std::shared_ptr; struct value_undefined_t : public value_t { + static constexpr auto kind_id = value_kind::UNDEFINED; std::string hint; // for debugging, to indicate where undefined came from - value_undefined_t(const std::string & h = "") : hint(h) {} + value_undefined_t(const std::string & h = "") : value_t(kind_id), hint(h) {} virtual std::string type() const override { return hint.empty() ? "Undefined" : "Undefined (hint: '" + hint + "')"; } virtual bool is_undefined() const override { return true; } virtual bool as_bool() const override { return false; } @@ -705,12 +751,14 @@ struct func_args { }; struct value_func_t : public value_t { + static constexpr auto kind_id = value_kind::FUNCTION; + func_handler val_func; std::string name; value arg0; // bound "this" argument, if any - value_func_t(const std::string & name, const func_handler & func) : name(name) { + value_func_t(const std::string & name, const func_handler & func) : value_t(kind_id), name(name) { val_func = func; } - value_func_t(const std::string & name, const func_handler & func, const value & arg_this) : name(name), arg0(arg_this) { + value_func_t(const std::string & name, const func_handler & func, const value & arg_this) : value_t(kind_id), name(name), arg0(arg_this) { val_func = func; } virtual value invoke(const func_args & args) const override { @@ -735,18 +783,22 @@ struct value_func_t : public value_t { // Note: this is unused for now, we don't support function as object keys // compare function pointers // (val_func == other.val_func does not work as std::function::operator== is only used for nullptr check) + if (kind != other.kind) { + return false; + } const auto target_this = this->val_func.target(); - const auto target_other = other.val_func.target(); - return typeid(*this) == typeid(other) && target_this == target_other; + const auto target_other = static_cast(other).val_func.target(); + return target_this == target_other; } }; using value_func = std::shared_ptr; // special value for kwarg struct value_kwarg_t : public value_t { + static constexpr auto kind_id = value_kind::KEYWORD; std::string key; value val; - value_kwarg_t(const std::string & k, const value & v) : key(k), val(v) {} + value_kwarg_t(const std::string & k, const value & v) : value_t(kind_id), key(k), val(v) {} virtual std::string type() const override { return "KwArg"; } virtual std::string as_repr() const override { return type(); } virtual bool is_hashable() const override { return true; } @@ -760,7 +812,7 @@ struct value_kwarg_t : public value_t { protected: virtual bool equivalent(const value_t & other) const override { const value_kwarg_t & other_val = static_cast(other); - return typeid(*this) == typeid(other) && key == other_val.key && val == other_val.val; + return kind == other.kind && key == other_val.key && val == other_val.val; } }; using value_kwarg = std::shared_ptr; diff --git a/common/parsers/gemma4.cpp b/common/parsers/gemma4.cpp index 5902e290bbc6..2a2e929e19a3 100644 --- a/common/parsers/gemma4.cpp +++ b/common/parsers/gemma4.cpp @@ -303,7 +303,8 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template & data.format = COMMON_CHAT_FORMAT_PEG_GEMMA4; data.supports_thinking = true; data.thinking_start_tag = "<|channel>thought"; - data.thinking_end_tags = {""}; + // a tool call may start before the thought channel is closed; stays first, the budget sampler forces it + data.thinking_end_tags = {"", "<|tool_call>"}; data.preserved_tokens = { "<|channel>", @@ -334,9 +335,10 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template & auto start = p.rule("start", p.optional(p.literal("<|turn>model\n"))); if (extract_reasoning) { - p.rule("thought", p.literal("<|channel>thought") + p.space() + p.reasoning(p.until("")) + p.literal("")); + // the model may start a tool call before closing the thought channel + p.rule("thought", p.literal("<|channel>thought") + p.space() + p.reasoning(p.until_one_of({"", "<|tool_call>"})) + (p.literal("") | p.peek(p.literal("<|tool_call>")))); } else { - p.rule("thought", p.content(p.literal("<|channel>thought") + p.space() + p.until("") + p.literal(""))); + p.rule("thought", p.content(p.literal("<|channel>thought") + p.space() + p.until_one_of({"", "<|tool_call>"}) + (p.literal("") | p.peek(p.literal("<|tool_call>"))))); } auto consume_empty_channels = p.gbnf(p.zero_or_more(p.literal("<|channel>") + p.negate(p.literal("thought"))), ""); diff --git a/common/parsers/inkling.cpp b/common/parsers/inkling.cpp new file mode 100644 index 000000000000..9c30cdb87962 --- /dev/null +++ b/common/parsers/inkling.cpp @@ -0,0 +1,165 @@ +#include "parsers.h" + +bool is_inkling_template(const std::string & src) { + return src.find("<|message_user|>") != std::string::npos && + src.find("<|content_image|>") != std::string::npos; +} + +// the template makes one message block per content part, but a media marker comes inside the text of a message +//
<|content_text|>{media}text<|end_message|> -->
{media}<|end_message|>
<|content_text|>text<|end_message|> +static void inkling_split_media(common_chat_prompt & prompt) { + const std::string TEXT = "<|content_text|>"; + const std::string END = "<|end_message|>"; + const std::string MEDIA_BEG = "<__media_"; + const std::string MEDIA_END = "__>"; + + std::vector out; + for (size_t i = 0; i < prompt.parts.size(); i++) { + const auto & part = prompt.parts[i]; + const bool in_text_block = part.is_input && part.text.find(MEDIA_BEG) != std::string::npos && + !out.empty() && !out.back().is_input && string_ends_with(out.back().text, TEXT) && + i + 1 < prompt.parts.size() && !prompt.parts[i + 1].is_input && string_starts_with(prompt.parts[i + 1].text, END); + const size_t header_pos = in_text_block ? out.back().text.rfind("<|message_") : std::string::npos; + if (header_pos == std::string::npos) { + out.push_back(part); + continue; + } + const std::string header = out.back().text.substr(header_pos, out.back().text.size() - TEXT.size() - header_pos); + + std::string rest = part.text; + for (bool first = true; !rest.empty(); first = false) { + const size_t beg = rest.find(MEDIA_BEG); + const size_t end = beg == std::string::npos ? beg : rest.find(MEDIA_END, beg); + const bool is_media = beg == 0 && end != std::string::npos; + const size_t len = is_media ? end + MEDIA_END.size() : (end == std::string::npos ? rest.size() : beg); + if (!first) { + out.push_back({ END + header + (is_media ? "" : TEXT), false }); + } else if (is_media) { + // mtmd opens the media block + out.back().text.resize(out.back().text.size() - TEXT.size()); + } + out.push_back({ rest.substr(0, len), true }); + rest.erase(0, len); + } + } + prompt.parts = std::move(out); +} + +// Inkling 1 and 2 - the assistant turn is a list of blocks, all closed by <|end_message|>: +// <|message_model|><|content_thinking|>...<|end_message|> +// <|message_model|><|content_text|>...<|end_message|> +// <|message_model|>NAME<|content_invoke_tool_json|>{"name":"NAME","args":{...}}<|end_message|> +common_chat_params common_chat_params_init_inkling(const common_chat_template & tmpl, + const autoparser::generation_params & inputs) { + common_chat_params data; + + data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs); + data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs); + data.format = COMMON_CHAT_FORMAT_PEG_NATIVE; + data.supports_thinking = true; + + inkling_split_media(data.prompt); + + const std::string HEADER = "<|message_model|>"; + const std::string THINK = "<|content_thinking|>"; + const std::string TEXT = "<|content_text|>"; + const std::string TOOL_JSON = "<|content_invoke_tool_json|>"; + const std::string END = "<|end_message|>"; + + data.preserved_tokens = { HEADER, THINK, TEXT, TOOL_JSON, END }; + + data.thinking_start_tag = THINK; + data.thinking_end_tags = { END }; + + data.message_delimiters = { + { COMMON_CHAT_ROLE_ASSISTANT, HEADER }, + { COMMON_CHAT_ROLE_USER, "<|message_user|>" }, + { COMMON_CHAT_ROLE_SYSTEM, "<|message_system|>" }, + { COMMON_CHAT_ROLE_TOOL, "<|message_tool|>" }, + }; + + if (inputs.has_continuation()) { + const auto & msg = inputs.continue_msg; + + data.generation_prompt.clear(); + if (!msg.reasoning_content.empty()) { + data.generation_prompt = HEADER + THINK + msg.reasoning_content; + } + if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) { + if (!data.generation_prompt.empty()) { + data.generation_prompt += END; + } + data.generation_prompt += HEADER + TEXT + msg.render_content(); + } + + data.prompt.append(data.generation_prompt); + } + + auto has_tools = inputs.tools.is_array() && !inputs.tools.empty(); + auto has_response_format = !inputs.json_schema.is_null() && inputs.json_schema.is_object(); + auto use_tools = has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE; + auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE; + + data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { + auto header = p.literal(HEADER); + auto end = p.literal(END); + + auto think = p.literal(THINK); + auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(END)) + end : + p.atomic(p.content(think)) + p.content(p.until(END) + end)); + auto text = p.rule("text", p.literal(TEXT) + p.content(p.until(END)) + end); + + if (has_response_format) { + auto response_format = p.rule("response-format", p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema))); + return p.zero_or_more(header + thinking) + header + p.literal(TEXT) + response_format + end; + } + + auto blocks = p.zero_or_more(header + (thinking | text)); + + if (!use_tools) { + return blocks; + } + + auto tool_choice = p.choice(); + foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { + const auto & function = tool.at("function"); + std::string name = function.at("name"); + + auto open = p.tool_name(p.literal(name)) + p.literal(TOOL_JSON) + p.literal("{\"name\":" + json(name).dump() + ",\"args\":"); + auto args = p.tool_args(p.json()); + + tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.tool_open(open) + args + p.tool_close(p.literal("}")) + end)); + }); + + // tool calls are the last blocks of the turn + auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice; + auto tool_calls = header + p.trigger_rule("tool-calls", calls); + + if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) { + return blocks + tool_calls; + } + + return blocks + p.optional(tool_calls); + }); + + if (has_response_format || use_tools) { + data.grammar_lazy = !has_response_format && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED; + data.grammar = build_grammar([&](const common_grammar_builder & builder) { + data.parser.build_grammar(builder, data.grammar_lazy); + }); + + if (data.grammar_lazy) { + // a header followed by text and not by a content token is a tool call, the grammar starts at the name + data.grammar_triggers = { + { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|message_model\\|>([^<])" }, + }; + // Inkling 1: the first header is in the generation prompt, and a lazy grammar does not get the prompt. + // an output that starts with no content token is a tool call. not for a continuation, it starts with text + if (!inputs.has_continuation()) { + data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL, "[^<]+" }); + } + } + } + + return data; +} diff --git a/common/parsers/lfm2.cpp b/common/parsers/lfm2.cpp index 1bb1e672879e..3ecd9573d82c 100644 --- a/common/parsers/lfm2.cpp +++ b/common/parsers/lfm2.cpp @@ -83,7 +83,8 @@ common_chat_params common_chat_params_init_lfm2(const common_chat_template & auto tool_calls = p.rule("tool-calls", p.trigger_rule("tool-call", p.literal(TOOL_CALL_START) + - p.python_style_tool_calls(inputs.tools, inputs.parallel_tool_calls, /* allow_json_literals = */ true) + + p.python_style_tool_calls(inputs.tools, inputs.parallel_tool_calls, /* allow_json_literals = */ true, + /* allow_undeclared = */ true) + p.literal(TOOL_CALL_END) ) ); diff --git a/common/parsers/ministral3.cpp b/common/parsers/ministral3.cpp index c865a3cae40a..9a37d0299845 100644 --- a/common/parsers/ministral3.cpp +++ b/common/parsers/ministral3.cpp @@ -50,7 +50,7 @@ common_chat_params common_chat_params_init_ministral_3(const common_chat_templat data.supports_thinking = true; data.thinking_start_tag = "[THINK]"; - data.thinking_end_tags = {"[/THINK]"}; + data.thinking_end_tags = {"[/THINK]", "[TOOL_CALLS]"}; data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs, /* messages_override = */ adjusted_messages); data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, /* messages_override = */ adjusted_messages); data.format = COMMON_CHAT_FORMAT_PEG_NATIVE; @@ -75,7 +75,7 @@ common_chat_params common_chat_params_init_ministral_3(const common_chat_templat data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { auto generation_prompt = p.eps(); auto reasoning = - extract_reasoning ? p.optional("[THINK]" + p.reasoning(p.until("[/THINK]")) + "[/THINK]") : p.eps(); + extract_reasoning ? p.optional("[THINK]" + p.reasoning(p.until_one_of({"[/THINK]", "[TOOL_CALLS]"})) + p.choice({p.literal("[/THINK]"), p.peek(p.literal("[TOOL_CALLS]"))})) : p.eps(); // Response format parser if (has_response_format) { diff --git a/common/parsers/parsers.h b/common/parsers/parsers.h index b1b6d166a124..867403370968 100644 --- a/common/parsers/parsers.h +++ b/common/parsers/parsers.h @@ -41,6 +41,8 @@ std::string common_chat_template_generation_prompt_impl( bool is_lfm2_template(const std::string & src); +bool is_inkling_template(const std::string & src); + common_chat_params common_chat_params_init_cohere2moe(const common_chat_template & tmpl, const autoparser::generation_params & inputs); common_chat_params common_chat_params_init_deepseek_v3_2(const common_chat_template & tmpl, const autoparser::generation_params & inputs); @@ -55,6 +57,8 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template & common_chat_params common_chat_params_init_harmony_xml(const common_chat_template & tmpl, const autoparser::generation_params & inputs); +common_chat_params common_chat_params_init_inkling(const common_chat_template & tmpl, const autoparser::generation_params & inputs); + common_chat_params common_chat_params_init_k2_horizon(const common_chat_template & tmpl, const autoparser::generation_params & inputs); common_chat_params common_chat_params_init_kimi_k2(const common_chat_template & tmpl, const autoparser::generation_params & inputs); diff --git a/common/parsers/sources.cmake b/common/parsers/sources.cmake index 2174f4519a64..934e22673e89 100644 --- a/common/parsers/sources.cmake +++ b/common/parsers/sources.cmake @@ -10,6 +10,7 @@ set(LLAMA_CHAT_PARSERS_SOURCES ${CMAKE_CURRENT_LIST_DIR}/gigachat-v3.cpp ${CMAKE_CURRENT_LIST_DIR}/gpt-oss.cpp ${CMAKE_CURRENT_LIST_DIR}/harmony-xml.cpp + ${CMAKE_CURRENT_LIST_DIR}/inkling.cpp ${CMAKE_CURRENT_LIST_DIR}/k2-horizon.cpp ${CMAKE_CURRENT_LIST_DIR}/kimi-k2.cpp ${CMAKE_CURRENT_LIST_DIR}/kimi-k3.cpp diff --git a/common/peg-parser.cpp b/common/peg-parser.cpp index e2ccb77bb14f..d980cfc76dca 100644 --- a/common/peg-parser.cpp +++ b/common/peg-parser.cpp @@ -1003,9 +1003,9 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id } else if constexpr (std::is_same_v) { return "Ref(" + p.name + ")"; } else if constexpr (std::is_same_v) { - return "Tag(" + p.tag + ", " + dump(p.child) + ")"; + return "Tag(" + p.tag + ", " + dump_impl(p.child, visited) + ")"; } else if constexpr (std::is_same_v) { - return "Atomic(" + dump(p.child) + ")"; + return "Atomic(" + dump_impl(p.child, visited) + ")"; } else { return "Unknown"; } diff --git a/common/sampling.cpp b/common/sampling.cpp index 4cbafbdad338..fe47097875db 100644 --- a/common/sampling.cpp +++ b/common/sampling.cpp @@ -324,6 +324,13 @@ struct common_sampler * common_sampler_init( throw std::invalid_argument("penalty_present must be finite"); } const llama_vocab * vocab = llama_model_get_vocab(model); + if (!common_grammar_value(params.grammar).empty()) { + for (const auto & b : params.logit_bias) { + if (b.bias == -INFINITY && llama_vocab_is_eog(vocab, b.token)) { + throw std::invalid_argument("EOG tokens cannot be banned when a grammar is set"); + } + } + } llama_sampler_chain_params lparams = llama_sampler_chain_default_params(); lparams.no_perf = params.no_perf; @@ -376,7 +383,8 @@ struct common_sampler * common_sampler_init( break; } default: - GGML_ASSERT(false && "unknown trigger type"); + throw std::runtime_error( + "unknown grammar trigger type: " + std::to_string(trigger.type)); } } diff --git a/common/speculative.cpp b/common/speculative.cpp index dbdadb1ea056..69dd5b43e709 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -70,17 +70,19 @@ static void spec_retune( } const std::map common_speculative_type_from_name_map = { - {"none", COMMON_SPECULATIVE_TYPE_NONE}, - {"draft-simple", COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE}, - {"draft-eagle3", COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3}, - {"draft-mtp", COMMON_SPECULATIVE_TYPE_DRAFT_MTP}, - {"draft-dflash", COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH}, - {"draft-dspark", COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK}, - {"ngram-simple", COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE}, - {"ngram-map-k", COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K}, - {"ngram-map-k4v", COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V}, - {"ngram-mod", COMMON_SPECULATIVE_TYPE_NGRAM_MOD}, - {"ngram-cache", COMMON_SPECULATIVE_TYPE_NGRAM_CACHE} + {"none", COMMON_SPECULATIVE_TYPE_NONE}, + {"draft-simple", COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE}, + {"draft-eagle3", COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3}, + {"draft-mtp", COMMON_SPECULATIVE_TYPE_DRAFT_MTP}, + {"draft-dflash", COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH}, + {"draft-dspark", COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK}, + {"draft-dflash2", COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2}, + {"draft-lilicorr", COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR}, + {"ngram-simple", COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE}, + {"ngram-map-k", COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K}, + {"ngram-map-k4v", COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V}, + {"ngram-mod", COMMON_SPECULATIVE_TYPE_NGRAM_MOD}, + {"ngram-cache", COMMON_SPECULATIVE_TYPE_NGRAM_CACHE} }; static std::string common_speculative_get_devices_str(const std::vector & devices) { @@ -1004,26 +1006,6 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { int32_t block_size = 0; llama_token mask_token_id = 0; - bool is_lilicorr = false; - int32_t lilicorr_top_k = 0; - size_t lilicorr_rows = 0; - std::vector lilicorr_embd; - std::vector lilicorr_pos; - - bool is_dflash2 = false; - bool is_mrope = false; - int32_t selector_top_k = 0; - - // DFlash2 probabilistic drafting: one generator per sequence and the seed it was last seeded with (-1: reseed) - std::vector dflash2_rng; - std::vector dflash2_seed; - - // draft-dspark: the draft carries a Markov head and uses an anchor-first block layout - const bool is_dspark; - - // dspark speculators - bool sample_from_anchor = true; - // block-internal attention bool causal_attn = false; @@ -1033,11 +1015,31 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { // inject target features from the target's device buffer instead of host copies (env LLAMA_DFLASH_DEV=0 disables) bool use_dev_features = false; + common_speculative_impl_draft_dflash(const common_params_speculative & params, uint32_t n_seq) + : common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH) + { + // DFlash input is [id_last, * (block_size-1)]: in-place denoising yields at most block_size-1 draft tokens + init({ + /* .n_draft_max = */ block_size - 1, + /* .backend_sampling = */ true, + /* .dev_features = */ true, + /* .nextn_masked = */ true, + }); + } + +protected: + // what init() sets up, per draft type + struct dflash_options { + int32_t n_draft_max; // longest draft a block yields, n_max and n_min are clamped to it + bool backend_sampling; // the block logits can be sampled on the backend + bool dev_features; // the target features can come from the target's device buffer + bool nextn_masked; // h_nextn is only read at the output rows + }; + common_speculative_impl_draft_dflash(const common_params_speculative & params, uint32_t n_seq, - common_speculative_type type = COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH) + common_speculative_type type) : common_speculative_impl(type, n_seq, params.draft.n_max) , params(params.draft) - , is_dspark(type == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) { auto * ctx_tgt = this->params.ctx_tgt; auto * ctx_dft = this->params.ctx_dft; @@ -1061,48 +1063,26 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { if (llama_model_meta_val_str(model_dft, "dflash.block_size", buf, sizeof(buf)) >= 0) { block_size = std::atoi(buf); } - if (llama_model_meta_val_str(model_dft, "dflash.sample_from_anchor", buf, sizeof(buf)) >= 0) { - sample_from_anchor = std::strcmp(buf, "true") == 0; - } if (llama_model_meta_val_str(model_dft, "dflash.attention.causal", buf, sizeof(buf)) >= 0) { causal_attn = std::strcmp(buf, "true") == 0; } } - selector_top_k = llama_model_dflash_selector_top_k(model_dft); - is_dflash2 = selector_top_k > 0; - dflash2_rng.resize(n_seq); - dflash2_seed.assign(n_seq, -1); - char lilicorr_meta[32] = {}; - lilicorr_top_k = llama_model_meta_val_str(model_dft, "lilicorr.candidate_topk", lilicorr_meta, sizeof(lilicorr_meta)) >= 0 - ? std::atoi(lilicorr_meta) : 0; - is_lilicorr = lilicorr_top_k > 0; - if (is_lilicorr) { - lilicorr_rows = (size_t) block_size + 1; - const size_t lilicorr_slots = (size_t) n_seq * lilicorr_rows; - lilicorr_embd.resize(lilicorr_slots * (size_t) n_embd_dec); - lilicorr_pos.assign(lilicorr_slots, -1); - } mask_token_id = llama_vocab_mask(llama_model_get_vocab(model_dft)); - if (is_dspark && this->params.p_min > 0.0f) { - char buf[16] = {}; - const bool has_conf = - llama_model_meta_val_str(model_dft, "dflash.has_confidence_head", buf, sizeof(buf)) < 0 || - std::strcmp(buf, "true") == 0; - if (!has_conf) { - throw std::runtime_error("DSpark draft has no confidence head: please set --spec-draft-p-min 0"); - } - } - LOG_INF("%s: adding speculative implementation '%s'\n", __func__, common_speculative_type_to_str(type).c_str()); LOG_INF("%s: - n_max=%d, n_min=%d, p_min=%.2f\n", __func__, this->params.n_max, this->params.n_min, this->params.p_min); - LOG_INF("%s: - block_size=%d, mask_token_id=%d, n_extract=%u, sample_from_anchor=%s\n", __func__, - block_size, mask_token_id, target_layer_ids_n, sample_from_anchor ? "true" : "false"); + LOG_INF("%s: - block_size=%d, mask_token_id=%d, n_extract=%u\n", __func__, + block_size, mask_token_id, target_layer_ids_n); + } - // DFlash input is [id_last, * (block_size-1)]: in-place denoising yields at most - // block_size-1 draft tokens, anchor-first DSpark yields a full block_size draft tokens - const int32_t n_draft_max = is_dspark && sample_from_anchor ? block_size : block_size - 1; + void init(const dflash_options & opt) { + auto * ctx_tgt = this->params.ctx_tgt; + auto * ctx_dft = this->params.ctx_dft; + + const llama_model * model_dft = llama_get_model(ctx_dft); + + const int32_t n_draft_max = opt.n_draft_max; if (this->params.n_max > n_draft_max || this->params.n_min > n_draft_max) { LOG_WRN("%s: requested draft size (n_max=%d, n_min=%d) exceeds the trained block size %d -- clamping to %d\n", __func__, this->params.n_max, this->params.n_min, block_size, n_draft_max); @@ -1114,9 +1094,6 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { batch = common_batch(ctx_dft); batch_inject = common_batch(ctx_dft); - // embd batches on an M-RoPE draft carry 4 position rows per token - is_mrope = llama_model_rope_type(model_dft) == LLAMA_ROPE_TYPE_MROPE; - smpls.resize(n_seq); for (auto & s : smpls) { common_params_sampling sparams; @@ -1128,7 +1105,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { // offload draft sampling to the backend backend_chains.assign(n_seq, nullptr); - if (this->params.backend_sampling && !is_dflash2 && !is_lilicorr) { + if (this->params.backend_sampling && opt.backend_sampling) { for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { llama_sampler * chain = llama_sampler_chain_init(llama_sampler_chain_default_params()); llama_sampler_chain_add(chain, llama_sampler_init_top_k(10)); @@ -1153,7 +1130,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { const bool ascending = std::adjacent_find(target_layer_ids, target_layer_ids + target_layer_ids_n, [](int32_t a, int32_t b) { return a >= b; }) == target_layer_ids + target_layer_ids_n; - use_dev_features = !is_lilicorr && ascending && (env == nullptr || atoi(env) != 0); + use_dev_features = opt.dev_features && ascending && (env == nullptr || atoi(env) != 0); if (use_dev_features) { llama_set_embeddings_layer_inp_dev(ctx_tgt, true); use_dev_features = llama_supports_embd_row(ctx_dft); @@ -1164,11 +1141,15 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { LOG_INF("%s: DFlash target features via %s\n", __func__, use_dev_features ? "device buffer" : "host copies"); } - // DFlash2 reads its selector lattice from h_nextn and never consumes raw logits. - llama_set_embeddings_nextn(ctx_dft, true, /*masked*/ !is_dflash2 && !is_lilicorr); + llama_set_embeddings_nextn(ctx_dft, true, opt.nextn_masked); llama_set_causal_attn(ctx_dft, causal_attn); // DFlash needs non-causal attention unless the model says otherwise } + // only LiliCorr uses this, to keep the context features for its scorer; the other heads only need the KV cache + // called after the host copy injection of a chunk, while h_nextn still holds the context features of batch_inject + virtual void store_context_features(llama_seq_id /*seq_id*/, int32_t /*n_chunk*/) {} + +public: ~common_speculative_impl_draft_dflash() override { auto * ctx_dft = this->params.ctx_dft; for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) backend_chains.size(); ++seq_id) { @@ -1188,9 +1169,6 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { return; } - // reseed per request rather than per round, or two identical requests differ - dflash2_seed[seq_id] = -1; - const int32_t N = (int32_t) prompt.size(); if (N <= 0) { return; @@ -1326,24 +1304,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { __func__, rc, (int) n_chunk, (int) offset); return false; } - if (is_lilicorr) { - // Ordinary DFlash can write to the KV cache, but LiliCorr needs to store embeddings across sequences. - const float * projected = llama_get_embeddings_nextn(ctx_dft); - if (projected) { - const size_t seq_offset = (size_t) seq_id * lilicorr_rows; - const llama_pos pos_min = std::max(0, batch_inject.tokens.back().pos[0] - block_size); - for (int32_t i = 0; i < n_chunk; ++i) { - const llama_pos pos = batch_inject.tokens[i].pos[0]; - if (pos < pos_min) { - continue; - } - const size_t slot = seq_offset + (size_t) pos % lilicorr_rows; - std::memcpy(lilicorr_embd.data() + slot * (size_t) n_embd_dec, - projected + (size_t) i * n_embd_dec, (size_t) n_embd_dec * sizeof(float)); - lilicorr_pos[slot] = pos; - } - } - } + store_context_features(seq_id, n_chunk); } } @@ -1355,7 +1316,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { batch.clear(); - // build one batch holding every drafting sequence's noise block into a single decode) + // build one batch holding every drafting sequence's noise block into a single decode // record where each block starts and its size std::vector i_block_beg(n_seq, -1); std::vector n_block (n_seq, 0); @@ -1371,17 +1332,138 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { const int32_t n = (int32_t) dp.pos0; const int32_t n_draft = params.n_max; - const int32_t n_block_tokens = is_lilicorr ? block_size : n_draft + (is_dspark && sample_from_anchor ? 0 : 1); + const int32_t n_block_tokens = n_draft + 1; i_block_beg[seq_id] = batch.size(); n_block [seq_id] = n_block_tokens; for (int32_t i = 0; i < n_block_tokens; ++i) { - const int32_t idx = batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, !is_dflash2 && !is_lilicorr); - if (is_lilicorr) { - // For LiliCorr drafting batch, set state embeddings for use in the associated transformer head. - const llama_pos pos = dp.pos0 - 1; - const size_t slot = (size_t) seq_id * lilicorr_rows + (size_t) pos % lilicorr_rows; - batch.set_embd_state(idx, { lilicorr_embd.data() + slot * (size_t) n_embd_dec, 1, (size_t) n_embd_dec }); + batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true); + } + } + + if (batch.size() == 0) { + return; + } + + // decode all sequence's noise block in a single batch + int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + if (ret != 0) { + LOG_WRN("%s: llama_process returned %d\n", __func__, ret); + return; + } + + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (i_block_beg[seq_id] < 0) { + continue; + } + auto & dp = dparams[seq_id]; + + const float p_min = common_speculative_p_min(dp, params.p_min); + + const int32_t beg = i_block_beg[seq_id]; + const int32_t n_block_tokens = n_block[seq_id]; + + auto * smpl = smpls[seq_id].get(); + + auto & result = *dp.result; + + // greedily read the predicted block at this sequence's noise positions 1..n_block_tokens-1 + for (int32_t i = 1; i < n_block_tokens; ++i) { + common_sampler_sample(smpl, ctx_dft, beg + i, true); + + const auto * cur_p = common_sampler_get_candidates(smpl, true); + + for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) { + LOG_DBG(" - seq_id %d, draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n", + seq_id, k, i - 1, cur_p->data[k].id, cur_p->data[k].p, + common_token_to_piece(ctx_dft, cur_p->data[k].id).c_str()); + } + + const llama_token id = cur_p->data[0].id; + + if (cur_p->data[0].p < p_min) { + break; } + + common_sampler_accept(smpl, id, true); + + result.push_back(id); + } + + if (result.size() < (size_t) params.n_min) { + result.clear(); + } + } + } + + void accept(llama_seq_id /*seq_id*/, uint16_t /*n_accepted*/, bool /*is_other*/) override { + // noop + } +}; + +// DSpark: a semi-autoregressive Markov head (+ Confidence head) on the block, anchor-first block layout +struct common_speculative_impl_draft_dspark final : public common_speculative_impl_draft_dflash { + // bonus anchor (SpecForge exports) when false: slot 0 is a bonus token, not a prediction slot + bool sample_from_anchor = true; + + common_speculative_impl_draft_dspark(const common_params_speculative & params, uint32_t n_seq) + : common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) + { + const llama_model * model_dft = llama_get_model(this->params.ctx_dft); + + { + char buf[32] = {}; + if (llama_model_meta_val_str(model_dft, "dflash.sample_from_anchor", buf, sizeof(buf)) >= 0) { + sample_from_anchor = std::strcmp(buf, "true") == 0; + } + } + + if (this->params.p_min > 0.0f) { + char buf[16] = {}; + const bool has_conf = + llama_model_meta_val_str(model_dft, "dflash.has_confidence_head", buf, sizeof(buf)) < 0 || + std::strcmp(buf, "true") == 0; + if (!has_conf) { + throw std::runtime_error("DSpark draft has no confidence head: please set --spec-draft-p-min 0"); + } + } + + LOG_INF("%s: - sample_from_anchor=%s\n", __func__, sample_from_anchor ? "true" : "false"); + + // anchor-first DSpark yields a full block_size draft tokens + init({ + /* .n_draft_max = */ sample_from_anchor ? block_size : block_size - 1, + /* .backend_sampling = */ true, + /* .dev_features = */ true, + /* .nextn_masked = */ true, + }); + } + + void draft(common_speculative_draft_params_vec & dparams) override { + auto & ctx_dft = params.ctx_dft; + + batch.clear(); + + // build one batch holding every drafting sequence's noise block into a single decode + // record where each block starts and its size + std::vector i_block_beg(n_seq, -1); + std::vector n_block (n_seq, 0); + + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + auto & dp = dparams[seq_id]; + if (!dp.drafting) { + continue; + } + + common_sampler_reset(smpls[seq_id].get()); + + const int32_t n = (int32_t) dp.pos0; + + const int32_t n_draft = params.n_max; + const int32_t n_block_tokens = n_draft + (sample_from_anchor ? 0 : 1); + i_block_beg[seq_id] = batch.size(); + n_block [seq_id] = n_block_tokens; + for (int32_t i = 0; i < n_block_tokens; ++i) { + batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true); } } @@ -1411,136 +1493,331 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { auto & result = *dp.result; - if (is_dflash2 || is_lilicorr) { - // Both DFlash and LiliCorr greedily walk the candidate lattice. - const float * lattice = llama_get_embeddings_nextn(ctx_dft); - GGML_ASSERT(lattice && "DFlash2 selector produced no lattice"); + // DSpark: read from the first draft slot, truncate below the confidence threshold + const float * conf = p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr; + // bonus-anchor drafts read the mask positions only, like DFlash + const int32_t i_draft_beg = sample_from_anchor ? 0 : 1; + for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) { + const int32_t idx = beg + i; - // DFlash2 can instead sample each step and hand q to the verifier for rejection sampling - const bool sample = is_dflash2 && params.probabilistic && dp.result_q; + if (conf && conf[(size_t) idx * n_embd_dec] < p_min) { + break; + } + + common_sampler_sample(smpl, ctx_dft, idx, true); - // greedy keeps temperature 1, sampling uses the target's - const float temp = sample ? dp.temp : 1.0f; + const auto * cur_p = common_sampler_get_candidates(smpl, true); - if (sample && dflash2_seed[seq_id] != dp.seed) { - dflash2_seed[seq_id] = dp.seed; - // the default seed means random; mixed so it differs from the target's, as in spec_retune - dflash2_rng[seq_id].seed(dp.seed == LLAMA_DEFAULT_SEED ? std::random_device{}() : dp.seed ^ 0x85ebca6bu); + for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) { + LOG_DBG(" - seq_id %d, draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n", + seq_id, k, i, cur_p->data[k].id, cur_p->data[k].p, + common_token_to_piece(ctx_dft, cur_p->data[k].id).c_str()); } - std::vector probs; - std::vector sorted_idx; - - int32_t predecessor = 0; - for (int32_t i = 1; i < (is_dflash2 ? n_block_tokens : params.n_max + 1); ++i) { - const float * row = lattice + (size_t) (beg + i) * n_embd_dec; - const int32_t top_k = is_dflash2 ? selector_top_k : lilicorr_top_k; - const float * scores = row + top_k + (size_t) predecessor * top_k; - - predecessor = (int32_t) std::distance(scores, - std::max_element(scores, scores + top_k)); - if (p_min > 0.0f || sample) { - // softmax(scores / temp) at the argmax, i.e. 1 / sum(exp((s_k - s_max) / temp)) - probs.resize(top_k); - float sum = 0.0f; - for (int32_t k = 0; k < top_k; ++k) { - probs[k] = std::exp((scores[k] - scores[predecessor]) / temp); - sum += probs[k]; - } - if (1.0f / sum < p_min) { + const llama_token id = cur_p->data[0].id; + + common_sampler_accept(smpl, id, true); + + result.push_back(id); + } + + if (result.size() < (size_t) params.n_min) { + result.clear(); + } + } + } +}; + +// DFlash2: walks the lattice of the selector over the top-k candidates of the block +struct common_speculative_impl_draft_dflash2 final : public common_speculative_impl_draft_dflash { + int32_t selector_top_k = 0; + + // probabilistic drafting: one generator per sequence and the seed it was last seeded with (-1: reseed) + std::vector dflash2_rng; + std::vector dflash2_seed; + + common_speculative_impl_draft_dflash2(const common_params_speculative & params, uint32_t n_seq) + : common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2) + { + selector_top_k = llama_model_dflash_selector_top_k(llama_get_model(this->params.ctx_dft)); + dflash2_rng.resize(n_seq); + dflash2_seed.assign(n_seq, -1); + + // DFlash2 reads its selector lattice from h_nextn and never consumes raw logits + init({ + /* .n_draft_max = */ block_size - 1, + /* .backend_sampling = */ false, + /* .dev_features = */ true, + /* .nextn_masked = */ false, + }); + } + + void begin(llama_seq_id seq_id, const llama_tokens & prompt) override { + if (seq_id >= 0 && seq_id < (llama_seq_id) n_seq) { + // reseed per request rather than per round, or two identical requests differ + dflash2_seed[seq_id] = -1; + } + + common_speculative_impl_draft_dflash::begin(seq_id, prompt); + } + + void draft(common_speculative_draft_params_vec & dparams) override { + auto & ctx_dft = params.ctx_dft; + + batch.clear(); + + // build one batch holding every drafting sequence's noise block into a single decode + // record where each block starts and its size + std::vector i_block_beg(n_seq, -1); + std::vector n_block (n_seq, 0); + + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + auto & dp = dparams[seq_id]; + if (!dp.drafting) { + continue; + } + + common_sampler_reset(smpls[seq_id].get()); + + const int32_t n = (int32_t) dp.pos0; + + const int32_t n_draft = params.n_max; + const int32_t n_block_tokens = n_draft + 1; + i_block_beg[seq_id] = batch.size(); + n_block [seq_id] = n_block_tokens; + for (int32_t i = 0; i < n_block_tokens; ++i) { + batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, false); + } + } + + if (batch.size() == 0) { + return; + } + + // decode all sequence's noise block in a single batch + int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + if (ret != 0) { + LOG_WRN("%s: llama_process returned %d\n", __func__, ret); + return; + } + + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (i_block_beg[seq_id] < 0) { + continue; + } + auto & dp = dparams[seq_id]; + + const float p_min = common_speculative_p_min(dp, params.p_min); + + const int32_t beg = i_block_beg[seq_id]; + const int32_t n_block_tokens = n_block[seq_id]; + + auto & result = *dp.result; + + const float * lattice = llama_get_embeddings_nextn(ctx_dft); + GGML_ASSERT(lattice && "DFlash2 selector produced no lattice"); + + // DFlash2 can instead sample each step and hand q to the verifier for rejection sampling + const bool sample = params.probabilistic && dp.result_q; + + // greedy keeps temperature 1, sampling uses the target's + const float temp = sample ? dp.temp : 1.0f; + + if (sample && dflash2_seed[seq_id] != dp.seed) { + dflash2_seed[seq_id] = dp.seed; + // the default seed means random; mixed so it differs from the target's, as in spec_retune + dflash2_rng[seq_id].seed(dp.seed == LLAMA_DEFAULT_SEED ? std::random_device{}() : dp.seed ^ 0x85ebca6bu); + } + + std::vector probs; + std::vector sorted_idx; + + int32_t predecessor = 0; + for (int32_t i = 1; i < n_block_tokens; ++i) { + const float * row = lattice + (size_t) (beg + i) * n_embd_dec; + const int32_t top_k = selector_top_k; + const float * scores = row + top_k + (size_t) predecessor * top_k; + + predecessor = (int32_t) std::distance(scores, + std::max_element(scores, scores + top_k)); + if (p_min > 0.0f || sample) { + // softmax(scores / temp) at the argmax, i.e. 1 / sum(exp((s_k - s_max) / temp)) + probs.resize(top_k); + float sum = 0.0f; + for (int32_t k = 0; k < top_k; ++k) { + probs[k] = std::exp((scores[k] - scores[predecessor]) / temp); + sum += probs[k]; + } + if (1.0f / sum < p_min) { + break; + } + for (int32_t k = 0; k < top_k; ++k) { + probs[k] /= sum; + } + } + if (sample) { + // ggml_top_k leaves candidates unordered, so walk them by token id to keep a seed's draft stable + sorted_idx.resize(top_k); + for (int32_t k = 0; k < top_k; ++k) { + sorted_idx[k] = k; + } + std::sort(sorted_idx.begin(), sorted_idx.end(), [row](int32_t a, int32_t b) { return row[a] < row[b]; }); + + // a round-off overshoot keeps the argmax, which has q > 0 + double u = std::uniform_real_distribution(0.0, 1.0)(dflash2_rng[seq_id]); + for (const int32_t k : sorted_idx) { + u -= probs[k]; + if (u < 0.0) { + predecessor = k; break; } - for (int32_t k = 0; k < top_k; ++k) { - probs[k] /= sum; - } } - if (sample) { - // ggml_top_k leaves candidates unordered, so walk them by token id to keep a seed's draft stable - sorted_idx.resize(top_k); - for (int32_t k = 0; k < top_k; ++k) { - sorted_idx[k] = k; - } - std::sort(sorted_idx.begin(), sorted_idx.end(), [row](int32_t a, int32_t b) { return row[a] < row[b]; }); - - // a round-off overshoot keeps the argmax, which has q > 0 - double u = std::uniform_real_distribution(0.0, 1.0)(dflash2_rng[seq_id]); - for (const int32_t k : sorted_idx) { - u -= probs[k]; - if (u < 0.0) { - predecessor = k; - break; - } - } - auto & q = dp.result_q->emplace_back(); - q.reserve(top_k); - for (int32_t k = 0; k < top_k; ++k) { - q.push_back({ (llama_token) row[k], scores[k], probs[k] }); - } + auto & q = dp.result_q->emplace_back(); + q.reserve(top_k); + for (int32_t k = 0; k < top_k; ++k) { + q.push_back({ (llama_token) row[k], scores[k], probs[k] }); } - result.push_back((llama_token) row[predecessor]); } + result.push_back((llama_token) row[predecessor]); + } - if (result.size() < (size_t) params.n_min) { - result.clear(); - if (sample) { - dp.result_q->clear(); - } + if (result.size() < (size_t) params.n_min) { + result.clear(); + if (sample) { + dp.result_q->clear(); } - continue; } + } + } +}; - if (is_dspark) { - // DSpark: read from the first draft slot, truncate below the confidence threshold - const float * conf = p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr; - // bonus-anchor drafts read the mask positions only, like DFlash - const int32_t i_draft_beg = sample_from_anchor ? 0 : 1; - for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) { - const int32_t idx = beg + i; +// LiliCorr: walks the lattice of the scorer over the top-k candidates of the block, which reads the +// context features of the anchor; they come back from the injection and are kept per sequence +struct common_speculative_impl_draft_lilicorr final : public common_speculative_impl_draft_dflash { + int32_t lilicorr_top_k = 0; - if (conf && conf[(size_t) idx * n_embd_dec] < p_min) { - break; - } + // context features of the last lilicorr_rows positions of each sequence, indexed by position + size_t lilicorr_rows = 0; + std::vector lilicorr_embd; + std::vector lilicorr_pos; - common_sampler_sample(smpl, ctx_dft, idx, true); + common_speculative_impl_draft_lilicorr(const common_params_speculative & params, uint32_t n_seq) + : common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR) + { + char lilicorr_meta[32] = {}; + lilicorr_top_k = llama_model_meta_val_str(llama_get_model(this->params.ctx_dft), "lilicorr.candidate_topk", lilicorr_meta, sizeof(lilicorr_meta)) >= 0 + ? std::atoi(lilicorr_meta) : 0; + lilicorr_rows = (size_t) block_size + 1; + const size_t lilicorr_slots = (size_t) n_seq * lilicorr_rows; + lilicorr_embd.resize(lilicorr_slots * (size_t) n_embd_dec); + lilicorr_pos.assign(lilicorr_slots, -1); + + // the context features are read back from h_nextn after a host copy injection + init({ + /* .n_draft_max = */ block_size - 1, + /* .backend_sampling = */ false, + /* .dev_features = */ false, + /* .nextn_masked = */ false, + }); + } - const auto * cur_p = common_sampler_get_candidates(smpl, true); +protected: + void store_context_features(llama_seq_id seq_id, int32_t n_chunk) override { + // Ordinary DFlash can write to the KV cache, but LiliCorr needs to store embeddings across sequences. + const float * projected = llama_get_embeddings_nextn(params.ctx_dft); + if (projected) { + const size_t seq_offset = (size_t) seq_id * lilicorr_rows; + const llama_pos pos_min = std::max(0, batch_inject.tokens.back().pos[0] - block_size); + for (int32_t i = 0; i < n_chunk; ++i) { + const llama_pos pos = batch_inject.tokens[i].pos[0]; + if (pos < pos_min) { + continue; + } + const size_t slot = seq_offset + (size_t) pos % lilicorr_rows; + std::memcpy(lilicorr_embd.data() + slot * (size_t) n_embd_dec, + projected + (size_t) i * n_embd_dec, (size_t) n_embd_dec * sizeof(float)); + lilicorr_pos[slot] = pos; + } + } + } - for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) { - LOG_DBG(" - seq_id %d, draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n", - seq_id, k, i, cur_p->data[k].id, cur_p->data[k].p, - common_token_to_piece(ctx_dft, cur_p->data[k].id).c_str()); - } +public: + void draft(common_speculative_draft_params_vec & dparams) override { + auto & ctx_dft = params.ctx_dft; - const llama_token id = cur_p->data[0].id; + batch.clear(); - common_sampler_accept(smpl, id, true); + // build one batch holding every drafting sequence's noise block into a single decode + // record where each block starts, all blocks have the same size + std::vector i_block_beg(n_seq, -1); - result.push_back(id); - } - } else { - // greedily read the predicted block at this sequence's noise positions 1..n_block_tokens-1 - for (int32_t i = 1; i < n_block_tokens; ++i) { - common_sampler_sample(smpl, ctx_dft, beg + i, true); + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + auto & dp = dparams[seq_id]; + if (!dp.drafting) { + continue; + } - const auto * cur_p = common_sampler_get_candidates(smpl, true); + common_sampler_reset(smpls[seq_id].get()); - for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) { - LOG_DBG(" - seq_id %d, draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n", - seq_id, k, i - 1, cur_p->data[k].id, cur_p->data[k].p, - common_token_to_piece(ctx_dft, cur_p->data[k].id).c_str()); - } + const int32_t n = (int32_t) dp.pos0; - const llama_token id = cur_p->data[0].id; + // the scorer reads a full block + i_block_beg[seq_id] = batch.size(); + for (int32_t i = 0; i < block_size; ++i) { + const int32_t idx = batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, false); + // For LiliCorr drafting batch, set state embeddings for use in the associated transformer head. + const llama_pos pos = dp.pos0 - 1; + const size_t slot = (size_t) seq_id * lilicorr_rows + (size_t) pos % lilicorr_rows; + batch.set_embd_state(idx, { lilicorr_embd.data() + slot * (size_t) n_embd_dec, 1, (size_t) n_embd_dec }); + } + } - if (cur_p->data[0].p < p_min) { - break; - } + if (batch.size() == 0) { + return; + } + + // decode all sequence's noise block in a single batch + int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + if (ret != 0) { + LOG_WRN("%s: llama_process returned %d\n", __func__, ret); + return; + } + + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (i_block_beg[seq_id] < 0) { + continue; + } + auto & dp = dparams[seq_id]; - common_sampler_accept(smpl, id, true); + const float p_min = common_speculative_p_min(dp, params.p_min); - result.push_back(id); + const int32_t beg = i_block_beg[seq_id]; + + auto & result = *dp.result; + + const float * lattice = llama_get_embeddings_nextn(ctx_dft); + GGML_ASSERT(lattice && "LiliCorr scorer produced no lattice"); + + int32_t predecessor = 0; + for (int32_t i = 1; i < params.n_max + 1; ++i) { + const float * row = lattice + (size_t) (beg + i) * n_embd_dec; + const int32_t top_k = lilicorr_top_k; + const float * scores = row + top_k + (size_t) predecessor * top_k; + + predecessor = (int32_t) std::distance(scores, + std::max_element(scores, scores + top_k)); + if (p_min > 0.0f) { + // softmax(scores) at the argmax, i.e. 1 / sum(exp(s_k - s_max)) + float sum = 0.0f; + for (int32_t k = 0; k < top_k; ++k) { + sum += std::exp(scores[k] - scores[predecessor]); + } + if (1.0f / sum < p_min) { + break; + } } + result.push_back((llama_token) row[predecessor]); } if (result.size() < (size_t) params.n_min) { @@ -1548,10 +1825,6 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { } } } - - void accept(llama_seq_id /*seq_id*/, uint16_t /*n_accepted*/, bool /*is_other*/) override { - // noop - } }; struct common_speculative_impl_draft_mtp : public common_speculative_impl { @@ -2566,18 +2839,20 @@ const char * common_speculative_all_types_str() { std::string common_speculative_type_to_str(common_speculative_type type) { switch (type) { - case COMMON_SPECULATIVE_TYPE_NONE: return "none"; - case COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE: return "draft-simple"; - case COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3: return "draft-eagle3"; - case COMMON_SPECULATIVE_TYPE_DRAFT_MTP: return "draft-mtp"; - case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH: return "draft-dflash"; - case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: return "draft-dspark"; - case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: return "ngram-simple"; - case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K: return "ngram-map-k"; - case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V: return "ngram-map-k4v"; - case COMMON_SPECULATIVE_TYPE_NGRAM_MOD: return "ngram-mod"; - case COMMON_SPECULATIVE_TYPE_NGRAM_CACHE: return "ngram-cache"; - default: return "unknown"; + case COMMON_SPECULATIVE_TYPE_NONE: return "none"; + case COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE: return "draft-simple"; + case COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3: return "draft-eagle3"; + case COMMON_SPECULATIVE_TYPE_DRAFT_MTP: return "draft-mtp"; + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH: return "draft-dflash"; + case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: return "draft-dspark"; + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2: return "draft-dflash2"; + case COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR: return "draft-lilicorr"; + case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: return "ngram-simple"; + case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K: return "ngram-map-k"; + case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V: return "ngram-map-k4v"; + case COMMON_SPECULATIVE_TYPE_NGRAM_MOD: return "ngram-mod"; + case COMMON_SPECULATIVE_TYPE_NGRAM_CACHE: return "ngram-cache"; + default: return "unknown"; } } @@ -2635,10 +2910,8 @@ std::vector common_speculative_types_from_gguf(const st return {}; } - // the Markov head distinguishes draft-dspark from draft-dflash - const auto type = gguf_find_tensor(gguf_ctx.get(), "markov_w1.weight") >= 0 - ? COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK - : COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH; + // draft-dflash runs every DFlash family draft, the head of the loaded draft picks the driver + const auto type = COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH; SPC_INF("auto-detected speculative type '%s' from the draft model metadata\n", common_speculative_type_to_str(type).c_str()); @@ -2663,6 +2936,8 @@ int32_t common_speculative_n_max(const common_params_speculative * spec) { case COMMON_SPECULATIVE_TYPE_DRAFT_MTP: case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH: case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2: + case COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR: n_max = std::max(n_max, std::max(0, spec->draft.n_max)); break; case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: @@ -2834,7 +3109,10 @@ common_params common_base_params_to_speculative(const common_params & params) { const bool has_block_draft = std::any_of( params.speculative.types.begin(), params.speculative.types.end(), [](common_speculative_type t) { - return t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK; + return t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || + t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK || + t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2 || + t == COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR; }); if (has_block_draft) { // per-seq output positions: DFlash decodes anchor + n_max masks (n_max + 1); DSpark n_max -> +1 covers both @@ -2950,6 +3228,14 @@ common_speculative * common_speculative_init(common_params_speculative & params, { uint32_t enabled_configs = common_get_enabled_speculative_configs(params.types); + // the DFlash family types share the draft context, so one run uses at most one of them + const uint32_t dflash_configs = enabled_configs & ( + (1u << COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH) | (1u << COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) | + (1u << COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2) | (1u << COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR)); + if (dflash_configs & (dflash_configs - 1)) { + throw std::runtime_error("draft-dflash, draft-dflash2, draft-dspark and draft-lilicorr cannot be combined"); + } + auto add_config_if_enabled = [&](common_speculative_type type, bool available = true) { if (available && (enabled_configs & (1u << type))) { configs.emplace_back(type, params); @@ -2957,7 +3243,7 @@ common_speculative * common_speculative_init(common_params_speculative & params, }; // when adding a new type - update here the logic above - static_assert(COMMON_SPECULATIVE_TYPE_COUNT == 11); + static_assert(COMMON_SPECULATIVE_TYPE_COUNT == 13); // this list here defines the priority of the speculators // the one with highest priority are listed first @@ -2968,10 +3254,12 @@ common_speculative * common_speculative_init(common_params_speculative & params, add_config_if_enabled(COMMON_SPECULATIVE_TYPE_NGRAM_CACHE); add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE); - add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3, params.draft.ctx_dft != nullptr); - add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_MTP, params.draft.ctx_dft != nullptr); - add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH, params.draft.ctx_dft != nullptr); - add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_MTP, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR, params.draft.ctx_dft != nullptr); } std::vector> impls = {}; @@ -2992,13 +3280,43 @@ common_speculative * common_speculative_init(common_params_speculative & params, impls.push_back(std::make_unique(config.params, n_seq)); break; } - case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH: { - impls.push_back(std::make_unique(config.params, n_seq)); - break; - } - case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: { - impls.push_back(std::make_unique( - config.params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK)); + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH: + case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2: + case COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR: { + common_speculative_type type_model = COMMON_SPECULATIVE_TYPE_NONE; + switch (llama_model_dflash_variant(llama_get_model(config.params.draft.ctx_dft))) { + case LLAMA_DFLASH_VARIANT_DFLASH: type_model = COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH; break; + case LLAMA_DFLASH_VARIANT_DFLASH2: type_model = COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2; break; + case LLAMA_DFLASH_VARIANT_DSPARK: type_model = COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK; break; + case LLAMA_DFLASH_VARIANT_LILICORR: type_model = COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR; break; + case LLAMA_DFLASH_VARIANT_NONE: break; + } + if (type_model == COMMON_SPECULATIVE_TYPE_NONE) { + throw std::runtime_error(string_format("--spec-type %s requires a DFlash draft model", + common_speculative_type_to_str(config.type).c_str())); + } + + // draft-dflash runs every DFlash family draft, the other types must match the head of the draft + if (config.type != COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH && config.type != type_model) { + throw std::runtime_error(string_format("--spec-type %s does not match the draft model: use %s", + common_speculative_type_to_str(config.type).c_str(), common_speculative_type_to_str(type_model).c_str())); + } + + switch (type_model) { + case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: + impls.push_back(std::make_unique(config.params, n_seq)); + break; + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2: + impls.push_back(std::make_unique(config.params, n_seq)); + break; + case COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR: + impls.push_back(std::make_unique(config.params, n_seq)); + break; + default: + impls.push_back(std::make_unique(config.params, n_seq)); + break; + } break; } case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: { @@ -3051,8 +3369,8 @@ common_speculative * common_speculative_init(common_params_speculative & params, } // the n-gram drafters ignore p_min, and DSpark uses it as the cutoff of its confidence head - const bool uses_p_min = std::any_of(configs.begin(), configs.end(), [](const common_speculative_config & c) { - switch (c.type) { + const bool uses_p_min = std::any_of(impls.begin(), impls.end(), [](const auto & impl) { + switch (impl->type) { case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K: diff --git a/common/speculative.h b/common/speculative.h index 509f0b5cc3f9..fe453b2f1d70 100644 --- a/common/speculative.h +++ b/common/speculative.h @@ -73,7 +73,7 @@ struct common_speculative_draft_params { // the generated draft from the last _draft() call llama_tokens * result; - // candidate distribution per drafted token; set it to make draft-simple, draft-mtp and draft-dflash (DFlash2 only) sample + // candidate distribution per drafted token; set it to make draft-simple, draft-mtp and draft-dflash2 sample std::vector> * result_q = nullptr; // the target's temp and seed, read only when the drafter samples probabilistically diff --git a/conversion/__init__.py b/conversion/__init__.py index 6800093ae4be..1182c06be3c0 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -126,6 +126,7 @@ "GlmOcrForConditionalGeneration": "glm", "GptOssForCausalLM": "gpt_oss", "GraniteForCausalLM": "granite", + "Granite4VisionForConditionalGeneration": "granite", "GraniteMoeForCausalLM": "granite", "GraniteMoeHybridForCausalLM": "granite", "GraniteMoeSharedForCausalLM": "granite", @@ -137,6 +138,7 @@ "Grok1ForCausalLM": "grok", "GrokForCausalLM": "grok", "GroveMoeForCausalLM": "grovemoe", + "HiggsAudio3Model": "higgs_audio", "HunYuanDenseV1ForCausalLM": "hunyuan", "HunYuanMoEV1ForCausalLM": "hunyuan", "HunYuanVLForConditionalGeneration": "hunyuan", @@ -144,6 +146,8 @@ "HYV3ForCausalLM": "hunyuan", "HYV4ForCausalLM": "hy_v4", "IQuestCoderForCausalLM": "llama", + "Inkling2ForCausalLM": "inkling2", + "Inkling2ForConditionalGeneration": "inkling2", "InternLM2ForCausalLM": "internlm", "InternLM3ForCausalLM": "internlm", "JAISLMHeadModel": "jais", @@ -217,6 +221,7 @@ "MiniMaxM2ForCausalLM": "minimax", "MiniMaxM3SparseForCausalLM": "minimax", "MiniMaxM3SparseForConditionalGeneration": "minimax", + "DSparkMiniMaxDraftModel": "minimax", "Ministral3ForCausalLM": "mistral3", "Ministral3Model": "mistral3", "Mistral3ForConditionalGeneration": "mistral3", @@ -278,6 +283,12 @@ "Qwen3NextForCausalLM": "qwen", "Qwen3OmniMoeForConditionalGeneration": "qwen3vl", "PocketTTSModel": "pockettts", + "KokoroModel": "kokoro", + "TinyVocaModel": "tiny_voca", + "Zonos3Model": "zonos3", + "YuE2ForCausalLM": "yue2", + "VoxCPM2Model": "voxcpm", + "MiniMaxMusic3ForConditionalGeneration": "minimax_music3", "Qwen3TTSForConditionalGeneration": "qwen3tts", "Qwen3VLForConditionalGeneration": "qwen3vl", "Qwen3VLMoeForConditionalGeneration": "qwen3vl", @@ -320,6 +331,7 @@ "UMT5Model": "t5", "UltravoxModel": "ultravox", "UnlimitedOCRForCausalLM": "deepseek", + "VibeVoiceAsrForConditionalGeneration": "vibevoice_asr", "VLlama3ForCausalLM": "llama", "VllmDecision2Model": "vllm_decision2", "VoxtralForConditionalGeneration": "llama", @@ -329,6 +341,8 @@ "XverseForCausalLM": "xverse", "YoutuForCausalLM": "deepseek", "YoutuVLForConditionalGeneration": "deepseek", + "ZayaForCausalLM": "zaya1", + "fish_qwen3_omni": "fish_s2", "modeling_grove_moe.GroveMoeForCausalLM": "grovemoe", "modeling_sarvam_moe.SarvamMoEForCausalLM": "bailingmoe", } @@ -352,6 +366,10 @@ "EmbeddingGemma2Model": "gemma", "Exaone4_5_ForConditionalGeneration": "exaone", "FishOmniModel": "drama3", + "Zonos3Model": "zonos3", + "YuE2ForCausalLM": "yue2", + "VoxCPM2Model": "voxcpm", + "MiniMaxMusic3ForConditionalGeneration": "minimax_music3", "Gemma3ForConditionalGeneration": "gemma", "Gemma3nForConditionalGeneration": "gemma", "Gemma4ForConditionalGeneration": "gemma", @@ -366,8 +384,10 @@ "Granite4VisionForConditionalGeneration": "granite", "GraniteSpeechForConditionalGeneration": "granite", "GraniteSpeechPlusForConditionalGeneration": "granite", + "HiggsAudio3Model": "higgs_audio", "HunYuanVLForConditionalGeneration": "hunyuan", "Idefics3ForConditionalGeneration": "smolvlm", + "Inkling2ForConditionalGeneration": "inkling2", "InternVisionModel": "internvl", "JanusForConditionalGeneration": "januspro", "KimiK25ForConditionalGeneration": "kimivl", @@ -408,6 +428,8 @@ "Qwen3ASRForConditionalGeneration": "qwen3vl", "Qwen3OmniMoeForConditionalGeneration": "qwen3vl", "PocketTTSModel": "pockettts", + "KokoroModel": "kokoro", + "TinyVocaModel": "tiny_voca", "SopranoModel": "soprano", "Qwen3TTSForConditionalGeneration": "qwen3tts", "Qwen3VLForConditionalGeneration": "qwen3vl", @@ -424,9 +446,11 @@ "Step3p7ForConditionalGeneration": "step3", "UltravoxModel": "ultravox", "UnlimitedOCRForCausalLM": "deepseek", + "VibeVoiceAsrForConditionalGeneration": "vibevoice_asr", "VoxtralForConditionalGeneration": "ultravox", "VoxtralRealtimeForConditionalGeneration": "ultravox", "YoutuVLForConditionalGeneration": "youtuvl", + "fish_qwen3_omni": "fish_s2", } diff --git a/conversion/base.py b/conversion/base.py index 58ddb5defe55..7cfbff321e0d 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -398,6 +398,9 @@ def dequant_bitnet(weight: Tensor, scale: Tensor) -> Tensor: return data / scale.float() def dequant_simple(weight: Tensor, scale: Tensor, block_size: Sequence[int] | None = None) -> Tensor: + if scale.dtype == torch.uint8: + # E8M0 exponent stored as raw bytes (MXFP8) + scale = (scale.float() - 127.0).exp2() scale = scale.float() # ModelOpt block scales are pre-shaped for broadcasting, e.g. [out/128, 1, in/128, 1] @@ -538,7 +541,7 @@ def dequant_fp8(fp8_configs: list[dict[str, Any]] | None = None) -> None: s = self.model_tensors[name] self.model_tensors[weight_name] = lambda w=w, s=s: dequant_bitnet(w(), s()) tensors_to_remove.append(name) - elif quant_method in ("fp8", "bsgemm-moe"): # bsgemm-moe: drama-3, same block layout + elif quant_method in ("fp8", "bsgemm-moe", "mxfp8"): # bsgemm-moe: drama-3, same block layout block_size = quant_config.get("weight_block_size") for name in self.model_tensors.keys(): if name.endswith("_scale_inv"): @@ -650,6 +653,28 @@ def dequant_fp8(fp8_configs: list[dict[str, Any]] | None = None) -> None: raise NotImplementedError(f"Quant format {quant_format!r} for method {quant_method!r} is not yet supported") elif quant_method in ("modelopt", "modelopt_mixed"): dequant_fp8() + # FP8_PB_WO: one scale per block, the block size follows from the two shapes + for name in self.model_tensors.keys(): + if not name.endswith(".weight_scale_inv"): + continue + weight_name = name.removesuffix("_scale_inv") + if weight_name not in self.model_tensors: + tensors_to_remove.append(name) + continue + w = self.model_tensors[weight_name] + s = self.model_tensors[name] + if w().dtype != torch.float8_e4m3fn: + continue + w_shape, s_shape = w().shape, s().shape + block_size = None + if prod(s_shape) != 1: + if len(s_shape) != len(w_shape) or any(ws % ss for ws, ss in zip(w_shape, s_shape)): + raise ValueError(f"FP8 weight {weight_name!r} {list(w_shape)} is not tiled by its scale {list(s_shape)}") + block_size = [ws // ss for ws, ss in zip(w_shape, s_shape)] + self.model_tensors[weight_name] = lambda w=w, s=s, bs=block_size: dequant_simple(w(), s(), bs) + tensors_to_remove.append(name) + if self._fp8_as_q8: + self._fp8_dequantized.add(weight_name) elif quant_method is not None: raise NotImplementedError(f"Quant method is not yet supported: {quant_method!r}") @@ -1357,10 +1382,10 @@ def _generate_nvfp4_tensors(self): consumed.append(input_scale_name) # Check if this is a per-expert tensor - m = re.search(r'\.experts\.(\d+)\.(gate_proj|up_proj|down_proj)\.weight$', name) + m = re.search(r'\.experts\.(\d+)\.(gate_proj|up_proj|down_proj|w1|w2|w3)\.weight$', name) if m: expert_id = int(m.group(1)) - proj_type = m.group(2) + proj_type = {"w1": "gate_proj", "w2": "down_proj", "w3": "up_proj"}.get(m.group(2), m.group(2)) bid_m = re.search(r'\.layers\.(\d+)\.', name) bid = int(bid_m.group(1)) if bid_m else 0 key = (bid, proj_type) @@ -1451,6 +1476,8 @@ def prepare_tensors(self): quant_layers = quant_config.get("quantized_layers", quant_layers) or {} nvfp4_compressed_tensors = self._is_nvfp4_compressed_tensors(quant_method, quant_format, quant_groups) + # e.g. MXFP8 dense weights with compressed-tensors NVFP4 experts + nvfp4_compressed_tensors |= quantization_config.get("moe_quant_format") == "nvfp4-pack-quantized" self._nvfp4_global_algo = quant_algo @@ -1979,6 +2006,14 @@ def set_gguf_parameters(self): if (local_rope_theta := self.rope_parameters.get("sliding_attention", {}).get("rope_theta")) is not None: self.gguf_writer.add_rope_freq_base_swa(local_rope_theta) logger.info(f"gguf: rope theta swa = {local_rope_theta}") + # Add rope_pattern from no_rope_layers + if no_rope_layers := self.hparams.get("no_rope_layers"): + if len(no_rope_layers) == self.block_count: # "no_rope_layers": [0, 0, 0, 1] + rope_pattern = [bool(x) for x in no_rope_layers] + else: # "no_rope_layers": [3] + rope_pattern = [i not in no_rope_layers for i in range(self.block_count)] + self.gguf_writer.add_rope_pattern(rope_pattern) + logger.info(f"gguf: rope_pattern = {sum(rope_pattern)} RoPE layers / {len(rope_pattern)} total") if (f_rms_eps := self.find_hparam(["rms_norm_eps", "norm_eps"], optional=True)) is not None: self.gguf_writer.add_layer_norm_rms_eps(f_rms_eps) logger.info(f"gguf: rms norm epsilon = {f_rms_eps}") @@ -2432,6 +2467,9 @@ def get_vocab_base_pre(self, tokenizer) -> str: if chkhsh == "a9af07a84191f55098b248ae6f3dfe9e32d3190bebe8eafd91c1ddec9bc3449f": # ref: https://huggingface.co/IFM/K2-Horizon-36B res = "k2-horizon" + if chkhsh == "5635e1c8d621dff7b4825f41f2f97b6ceb39bcf2d5c541db28577080d6efd5e5": + # ref: https://huggingface.co/thinkingmachines/Inkling-2-Small + res = "inkling2" if res is None: logger.warning("\n") @@ -3461,7 +3499,7 @@ def get_model_architecture(hparams: dict[str, Any], model_type: ModelType) -> st # Kimi-K3's text_config reports "KimiLinearForCausalLM", which is the older # Kimi-Linear-48B architecture and cannot load K3 (no attention residuals, # latent MoE, situ, ...). Route on the top-level architecture instead. - if model_type == ModelType.TEXT and arch in ("NEOChatModel", "StepVLForConditionalGeneration", "Sarashina2VisionForCausalLM", "Exaone4_5_ForConditionalGeneration", "Step3p7ForConditionalGeneration", "KimiK3ForConditionalGeneration", "KimiK31ForConditionalGeneration", "Nemotron3_5TranscribeForConditionalGeneration"): + if model_type == ModelType.TEXT and arch in ("NEOChatModel", "StepVLForConditionalGeneration", "Sarashina2VisionForCausalLM", "Exaone4_5_ForConditionalGeneration", "Step3p7ForConditionalGeneration", "KimiK3ForConditionalGeneration", "KimiK31ForConditionalGeneration", "Nemotron3_5TranscribeForConditionalGeneration", "HiggsAudio3Model"): return arch # if "architectures" is found in the sub-config, use that instead @@ -3472,6 +3510,9 @@ def get_model_architecture(hparams: dict[str, Any], model_type: ModelType) -> st # some models (llava_onevision2) only declare the architecture inside text_config if arch is None and text_config.get("architectures") is not None: arch = text_config["architectures"][0] + # some configs only have a model_type (fishaudio/s2-pro) + if arch is None: + arch = hparams.get("model_type") if arch is None: raise ValueError("Failed to detect model architecture") return arch diff --git a/conversion/drama3.py b/conversion/drama3.py index ac01f481c98a..68bbb556bfd4 100644 --- a/conversion/drama3.py +++ b/conversion/drama3.py @@ -18,6 +18,30 @@ _TOWER_RESIDUAL = "audio_decoder_mtp.layers." +def load_codec(dir_model) -> dict[str, Tensor]: + sd = torch.load(dir_model / "codec.pth", map_location="cpu", mmap=True, weights_only=True) + return sd.get("state_dict", sd) + + +def fold_conv(sd: dict[str, Tensor], prefix: str) -> Tensor: + # fold weight norm + if prefix + ".conv.weight" in sd: + return sd[prefix + ".conv.weight"].float() + g = sd[prefix + ".conv.parametrizations.weight.original0"].float() + v = sd[prefix + ".conv.parametrizations.weight.original1"].float() + return g * v / v.norm(dim=(1, 2), keepdim=True) + + +def fold_wn(g: Tensor, v: Tensor) -> Tensor: + # fold old-style weight norm of a 1x1 conv, returns [out, in] + return (g.float() * v.float() / v.float().norm(dim=(1, 2), keepdim=True)).squeeze(-1) + + +def fold_snake(alpha: Tensor) -> tuple[Tensor, Tensor]: + alpha = alpha.float().flatten() + return alpha, 1.0 / (alpha + 1e-9) + + @ModelBase.register("FishOmniModel") @ModelBase.example("fishaudio/drama-3") class Drama3TextModel(Qwen3_5MoeTextModel): @@ -36,6 +60,7 @@ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Ca class Drama3MmprojModel(MmprojModel): has_vision_encoder = False has_audio_encoder = False + gen_projector_type = gguf.VisionProjectorType.DRAMA3_GEN _LAYER_MAP = { "enorm.weight": (gguf.MODEL_TENSOR.A_GEN_CODE_ENORM, True), @@ -69,7 +94,7 @@ def set_gguf_parameters(self): cfg = self.hparams self.gguf_writer.add_file_type(self.ftype) self.gguf_writer.add_clip_has_gen_audio_encoder(True) - self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.DRAMA3_GEN) + self.gguf_writer.add_clip_gen_audio_projector_type(self.gen_projector_type) self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text) self.gguf_writer.add_gen_audio_embedding_length(cfg["dim"]) self.gguf_writer.add_gen_audio_feed_forward_length(cfg["intermediate_size"]) @@ -153,32 +178,20 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: # only the DAC decoder, the encoder is for voice cloning (not supported yet) - sd = torch.load(self.dir_model / "codec.pth", map_location="cpu", mmap=True, weights_only=True) - sd = sd.get("state_dict", sd) + sd = load_codec(self.dir_model) T = gguf.MODEL_TENSOR def get(name: str) -> Tensor: return sd[name].float() def conv(prefix: str) -> Tensor: - # fold weight norm - if prefix + ".conv.weight" in sd: - return get(prefix + ".conv.weight") - g = get(prefix + ".conv.parametrizations.weight.original0") - v = get(prefix + ".conv.parametrizations.weight.original1") - return g * v / v.norm(dim=(1, 2), keepdim=True) + return fold_conv(sd, prefix) def quant_table(prefix: str) -> Tensor: # fold out_proj into the codebook, so decoding is a row lookup - g = get(prefix + ".out_proj.weight_g") - v = get(prefix + ".out_proj.weight_v") - w = (g * v / v.norm(dim=(1, 2), keepdim=True)).squeeze(-1) + w = fold_wn(sd[prefix + ".out_proj.weight_g"], sd[prefix + ".out_proj.weight_v"]) return get(prefix + ".codebook.weight") @ w.T + get(prefix + ".out_proj.bias") - def snake(alpha: Tensor) -> tuple[Tensor, Tensor]: - alpha = alpha.flatten() - return alpha, 1.0 / (alpha + 1e-9) - q = "quantizer." yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_FIRST_CB), quant_table(q + "semantic_quantizer.quantizers.0")) n_rest = sum(1 for k in sd if k.startswith(q + "quantizer.quantizers.") and k.endswith(".codebook.weight")) @@ -228,7 +241,7 @@ def neox_rows(w: Tensor) -> Tensor: yield (self.format_tensor_name(T.A_GEN_WAV_DAC_ENTRY, suffix=".bias"), get(d + "0.conv.bias")) for bid in range(4): p = f"{d}{bid + 1}.block." - a, b = snake(get(p + "0.alpha")) + a, b = fold_snake(get(p + "0.alpha")) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_UP_SNAKE, bid, suffix=".alpha"), a) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_UP_SNAKE, bid, suffix=".beta"), b) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_UP_CONV, bid, suffix=".weight"), conv(p + "1")) @@ -236,7 +249,7 @@ def neox_rows(w: Tensor) -> Tensor: for xid in range(3): r = f"{p}{xid + 2}.block." for act, tensor in (("0", T.A_GEN_WAV_DAC_RES_ACT1), ("2", T.A_GEN_WAV_DAC_RES_ACT2)): - a, b = snake(get(r + act + ".alpha")) + a, b = fold_snake(get(r + act + ".alpha")) name = gguf.TENSOR_NAMES[tensor].format(bid=bid, xid=xid) yield (name + ".alpha", a) yield (name + ".beta", b) @@ -244,7 +257,7 @@ def neox_rows(w: Tensor) -> Tensor: name = gguf.TENSOR_NAMES[tensor].format(bid=bid, xid=xid) yield (name + ".weight", conv(r + cv)) yield (name + ".bias", get(r + cv + ".conv.bias")) - a, b = snake(get(d + "5.alpha")) + a, b = fold_snake(get(d + "5.alpha")) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_POST_SNAKE, suffix=".alpha"), a) 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")) diff --git a/conversion/fish_s2.py b/conversion/fish_s2.py new file mode 100644 index 000000000000..4c5aeff13200 --- /dev/null +++ b/conversion/fish_s2.py @@ -0,0 +1,276 @@ +from __future__ import annotations + +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 .qwen import Qwen3Model + +# Fish Audio S2 Pro (dual-AR) +# text model: Qwen3 backbone (slow AR), samples the semantic code of each frame +# mmproj: fast AR code predictor (other codebooks) and Fish DAC decoder (codec.pth, same as drama3) + +# 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) + cfg = hparams["text_config"] + hparams["text_config"] = { + "hidden_size": cfg["dim"], + "num_hidden_layers": cfg["n_layer"], + "num_attention_heads": cfg["n_head"], + "num_key_value_heads": cfg["n_local_heads"], + "head_dim": cfg["head_dim"], + "intermediate_size": cfg["intermediate_size"], + "rms_norm_eps": cfg["norm_eps"], + "rope_theta": cfg["rope_base"], + "max_position_embeddings": cfg["max_seq_len"], + "vocab_size": cfg["vocab_size"], + "tie_word_embeddings": cfg["tie_word_embeddings"], + } + 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): + model_arch = gguf.MODEL_ARCH.QWEN3 + + def __init__(self, dir_model: Path, *args, **kwargs): + kwargs.pop("hparams", None) + super().__init__(dir_model, *args, hparams=_load_hparams(dir_model), **kwargs) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + # the rest is mapped by tensor_mapping.py + name = name.removeprefix("text_model.") + T = gguf.MODEL_TENSOR + head_dim = self.hparams["head_dim"] + if name.endswith(".attention.wqkv.weight"): + n_q = self.hparams["num_attention_heads"] * head_dim + n_kv = self.hparams["num_key_value_heads"] * head_dim + q, k, v = data_torch.split([n_q, n_kv, n_kv], dim=0) + yield (self.format_tensor_name(T.ATTN_Q, bid), _neox_rows(q, head_dim)) + yield (self.format_tensor_name(T.ATTN_K, bid), _neox_rows(k, head_dim)) + yield (self.format_tensor_name(T.ATTN_V, bid), v) + return + if name.endswith(".attention.q_norm.weight"): + yield (self.format_tensor_name(T.ATTN_Q_NORM, bid), _neox_rows(data_torch, head_dim)) + return + if name.endswith(".attention.k_norm.weight"): + yield (self.format_tensor_name(T.ATTN_K_NORM, bid), _neox_rows(data_torch, head_dim)) + return + yield from super().modify_tensors(data_torch, name, bid) + + +@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 = { + "attention_norm.weight": gguf.MODEL_TENSOR.A_GEN_CODE_ATTN_NORM, + "attention.wo.weight": gguf.MODEL_TENSOR.A_GEN_CODE_ATTN_OUT, + "ffn_norm.weight": gguf.MODEL_TENSOR.A_GEN_CODE_FFN_NORM, + "feed_forward.w1.weight": gguf.MODEL_TENSOR.A_GEN_CODE_FFN_GATE, + "feed_forward.w3.weight": gguf.MODEL_TENSOR.A_GEN_CODE_FFN_UP, + "feed_forward.w2.weight": gguf.MODEL_TENSOR.A_GEN_CODE_FFN_DOWN, + } + + def __init__(self, dir_model: Path, *args, **kwargs): + kwargs.pop("hparams", None) + super().__init__(dir_model, *args, hparams=_load_hparams(dir_model), **kwargs) + + def get_audio_config(self) -> dict[str, Any] | None: + cfg = dict(self.global_config["audio_decoder_config"]) + 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] + if name.startswith("audio_decoder.") or name == "text_model.model.embeddings.weight": + return item + return None + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + T = gguf.MODEL_TENSOR + cfg = self.hparams + + # already named by generate_extra_tensors() + if name.startswith("a."): + yield (name, data_torch) + return + + if name == "text_model.model.embeddings.weight": + # semantic band of the backbone embeddings + begin = self.global_config["semantic_start_token_id"] + yield (self.format_tensor_name(T.A_GEN_CODE_OUT_EMBD), data_torch[begin:begin + cfg["vocab_size"]]) + return + + if name == "audio_decoder.codebook_embeddings.weight": + # backbone input of a speech row, one table per codebook + yield (self.format_tensor_name(T.A_GEN_CODE_EMBD), data_torch.reshape(cfg["num_codebooks"], -1, data_torch.shape[-1])) + return + + if name == "audio_decoder.embeddings.weight": + yield (self.format_tensor_name(T.A_GEN_CODE_TOK_EMBD), data_torch) + return + + if name == "audio_decoder.output.weight": + yield (self.format_tensor_name(T.A_GEN_CODE_HEAD), data_torch[:_N_RESIDUAL_CODES]) + return + + if name == "audio_decoder.norm.weight": + yield (self.format_tensor_name(T.A_GEN_CODE_OUTPUT_NORM), data_torch) + return + + assert bid is not None and name.startswith(f"audio_decoder.layers.{bid}.") + key = name.removeprefix(f"audio_decoder.layers.{bid}.") + if key == "attention.wqkv.weight": + head_dim = cfg["head_dim"] + n_q = cfg["n_head"] * head_dim + n_kv = cfg["n_local_heads"] * head_dim + q, k, v = data_torch.split([n_q, n_kv, n_kv], dim=0) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_Q, bid), _neox_rows(q, head_dim)) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_K, bid), _neox_rows(k, head_dim)) + 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/granite.py b/conversion/granite.py index 4c6c5a0e4cc5..66b03ceca52c 100644 --- a/conversion/granite.py +++ b/conversion/granite.py @@ -14,7 +14,7 @@ from .mamba import Mamba2Model -@ModelBase.register("GraniteForCausalLM") +@ModelBase.register("GraniteForCausalLM", "Granite4VisionForConditionalGeneration") @ModelBase.example("ibm-granite/granite-3.3-2b-instruct") class GraniteModel(LlamaModel): """Conversion for IBM's GraniteForCausalLM""" @@ -112,14 +112,6 @@ def set_gguf_parameters(self): logger.info("gguf: (granite_swa) sliding_window_pattern (inferred) = %d SWA layers / %d total", sum(is_swa), n_layers) - # Add rope_pattern from no_rope_layers - if no_rope_layers := self.hparams.get("no_rope_layers"): - # Convert 1/0 to bool (1 = use RoPE, 0 = NoPE) - rope_pattern = [bool(x) for x in no_rope_layers] - self.gguf_writer.add_rope_pattern(rope_pattern) - logger.info("gguf: (granite_swa) rope_pattern = %d RoPE layers / %d total", - sum(rope_pattern), len(rope_pattern)) - @ModelBase.register("GraniteMoeSWAForCausalLM") class GraniteMoeSWAModel(GraniteSWAModel): @@ -560,7 +552,9 @@ def set_gguf_parameters(self): or not self._ssm_layers ) self.gguf_writer.add_rope_scaling_finetuned(use_rope) - if not use_rope: + # Set context length to an arbitrary large value if rope is not used AND no previous value is present. + # https://huggingface.co/ibm-granite/granite-4.0-h-micro-GGUF/discussions/1 + if not use_rope and "max_position_embeddings" not in self.hparams: self.gguf_writer.add_context_length(2**20) ## Validation ## diff --git a/conversion/higgs_audio.py b/conversion/higgs_audio.py new file mode 100644 index 000000000000..9e4d8b2b89ee --- /dev/null +++ b/conversion/higgs_audio.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import Any, Callable, TYPE_CHECKING + +if TYPE_CHECKING: + from torch import Tensor + +from .base import ModelBase, gguf +from .qwen import Qwen3Model +from .ultravox import WhisperEncoderModel + + +# plain ChatML as built by transcribe.py upstream, the Qwen3 template renders past assistant turns differently from the last one +HIGGS_AUDIO_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' -}}" + "{%- if enable_thinking is defined and enable_thinking is false -%}" + "{{- '\\n\\n\\n\\n' -}}" + "{%- endif -%}" + "{%- endif -%}" +) + + +@ModelBase.register("HiggsAudio3Model") +@ModelBase.example("bosonai/higgs-audio-v3-stt") +class HiggsAudioModel(Qwen3Model): + model_arch = gguf.MODEL_ARCH.QWEN3 + + def set_vocab(self): + super().set_vocab() + self.gguf_writer.add_chat_template(HIGGS_AUDIO_CHAT_TEMPLATE) + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, gen = item + + # the audio_* tensors are dropped by TextModel, rename the text head before that + if name == "audio_decoder_proj.text_lm_head.weight": + name = "lm_head.weight" + else: + name = "model." + name + + return super().filter_tensors((name, gen)) + + +@ModelBase.register("HiggsAudio3Model") +class HiggsAudioWhisperEncoderModel(WhisperEncoderModel): + has_vision_encoder = False + has_audio_encoder = True + + def get_audio_config(self) -> dict[str, Any] | None: + return self.global_config["audio_encoder_config"] + + def tensor_force_quant(self, name, new_name, bid, n_dims): + # depthwise conv kernel, same as the whisper convs + if name == "audio_encoder_proj.temporal.weight": + return gguf.GGMLQuantizationType.F16 + return super().tensor_force_quant(name, new_name, bid, n_dims) + + def set_gguf_parameters(self): + assert self.global_config["projector_type"] == "mlp" and self.global_config["projector_temporal_downsample"] == 2 + assert self.global_config["audio_adapter_type"] == "stack" and not self.global_config.get("duplicate_audio_triplet", False) + super().set_gguf_parameters() + self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.HIGGS_AUDIO) + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, _ = item + if not name.startswith(("audio_tower.", "audio_encoder_proj.")): + return None + return super().filter_tensors(item) diff --git a/conversion/inkling2.py b/conversion/inkling2.py new file mode 100644 index 000000000000..a8e8b892ed72 --- /dev/null +++ b/conversion/inkling2.py @@ -0,0 +1,331 @@ +from __future__ import annotations + +import json +import re +from pathlib import Path +from functools import partial +from typing import Callable, Iterable, TYPE_CHECKING, cast + +import numpy as np +import torch + +if TYPE_CHECKING: + from torch import Tensor + +from .base import LazyTorchTensor, ModelBase, MmprojModel, TextModel, gguf, logger + + +def _e4m3_table() -> np.ndarray: + codes = np.arange(256, dtype=np.uint8) + exponent = ((codes & 0x7F) >> 3).astype(np.int32) + mantissa = (codes & 7).astype(np.float32) + values = np.where(exponent == 0, np.ldexp(mantissa, -9), np.ldexp(1 + mantissa / 8, exponent - 7)) + values = np.where(codes & 0x80, -values, values) + values[(codes & 0x7F) == 0x7F] = np.nan + return values.astype(np.float32) + + +_E4M3 = _e4m3_table() +_E2M1 = np.array([0, 0.5, 1, 1.5, 2, 3, 4, 6, -0.0, -0.5, -1, -1.5, -2, -3, -4, -6], dtype=np.float32) +_EXPERT_CHUNK_ROWS = 128 + + +def _dequant_expert_chunk(weight: Callable[[], Tensor], scale: Callable[[], Tensor], amax: Callable[[], Tensor] | None, denominator: Callable[[], Tensor] | None, name: str, expert: int, rows: slice) -> np.ndarray: + # Fresh lazy tensors release their mappings after each chunk instead of caching the layer. + packed = LazyTorchTensor.to_eager(weight().view(torch.uint8)[expert, rows]).numpy() + scales = LazyTorchTensor.to_eager(scale().view(torch.uint8)[expert, rows]).numpy() + if amax is not None: + block_scale = _E4M3[scales] + if np.isnan(block_scale).any(): + raise ValueError(f"Inkling2: {name}_scale expert {expert}: E4M3FN NaN") + values = np.empty((packed.shape[0], packed.shape[1] * 2), dtype=np.float32) + values[:, 0::2] = _E2M1[packed & 15] + values[:, 1::2] = _E2M1[packed >> 4] + values.reshape(values.shape[0], -1, 16)[:] *= block_scale[:, :, None] + assert denominator is not None + a = LazyTorchTensor.to_eager(amax()[expert]).item() + d = LazyTorchTensor.to_eager(denominator()).item() + if not np.isfinite(a) or a < 0: + raise ValueError(f"Inkling2: {name}_amax expert {expert}: expected finite nonnegative value") + if not np.isfinite(d) or d <= 0: + raise ValueError(f"Inkling2: {name}_outer_scale_denominator expert {expert}: expected finite positive value") + with np.errstate(over="ignore", invalid="ignore"): + values *= np.float32(a) / np.float32(d) + else: + if np.any(scales == 255): + raise ValueError(f"Inkling2: {name}_scale expert {expert}: UE8M0 byte 255 is NaN") + values = _E4M3[packed] + if np.isnan(values).any(): + raise ValueError(f"Inkling2: {name} expert {expert}: E4M3FN NaN") + block_scale = np.ldexp(np.ones(scales.shape, dtype=np.float32), scales.astype(np.int32) - 127) + with np.errstate(over="ignore", invalid="ignore"): + values.reshape(values.shape[0], -1, 32)[:] *= block_scale[:, :, None] + if not np.isfinite(values).all(): + raise ValueError(f"Inkling2: {name} expert {expert}: non-finite dequantized weight") + return values + + +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") + + +@ModelBase.register_hparams_loader(_is_inkling2) +def _load_inkling2_hparams(dir_model: Path): + # AutoConfig injects MXFP8 defaults and can replace the original layer schedule. + with open(dir_model / "config.json", encoding="utf-8") as f: + return json.load(f) + + +@ModelBase.register("Inkling2ForConditionalGeneration", "Inkling2ForCausalLM") +@ModelBase.example("thinkingmachines/Inkling-2-Small") +class Inkling2Model(TextModel): + model_arch = gguf.MODEL_ARCH.INKLING2 + + def __init__(self, dir_model: Path, *args, **kwargs): + self._expert_quant: dict[str, dict] = {} + self._packed_experts: dict[str, gguf.LazyChunkedTensor] = {} + quant_path = dir_model / "hf_quant_config.json" + if quant_path.is_file(): + with open(quant_path, encoding="utf-8") as f: + groups = json.load(f).get("model", {}).get("parameter_groups", []) + for group in groups: + for name in group.get("tensors", []): + item = self.filter_tensors((name, lambda: torch.empty(0))) + if item is not None and item[0].endswith((".w13_weight", ".w2_weight")): + name = item[0] + if name in self._expert_quant: + raise ValueError(f"Inkling2: duplicate hf_quant_config.json scheme for {name}") + self._expert_quant[name] = group + super().__init__(dir_model, *args, **kwargs) + logger.warning("Inkling2: converting the text backbone only; vision and MTP tensors are skipped") + hp = self.hparams + for name, default in (("q_bias", False), ("o_bias", False), ("n_shared_experts", 0), ("use_value_norm_no_gamma", True), ("attn_res_normalize_values", True), ("scoring_func", "sigmoid")): + if hp.get(name, default) != default: + raise ValueError(f"Inkling2: unsupported {name}={hp[name]!r}") + types = hp.get("layer_types") + if types is None: + local = hp["local_layer_ids"] + types = ["hybrid_sliding" if i in local else "hybrid" for i in range(self.block_count)] + if len(types) != self.block_count or set(types) - {"hybrid", "hybrid_sliding"}: + raise ValueError("Inkling2: invalid layer_types") + self.is_swa = [t == "hybrid_sliding" for t in types] + + def dequant_model(self): + for name in list(self.model_tensors): + if not name.endswith((".w13_weight", ".w2_weight")): + continue + weight = self.model_tensors[name] + tensor = weight() + companions = [name + suffix for suffix in ("_scale", "_amax", "_outer_scale_denominator")] + if tensor.dtype.is_floating_point and tensor.element_size() > 1: + if any(n in self.model_tensors for n in companions): + raise ValueError(f"Inkling2: floating-point {name} has packed quantization companions") + continue + config = self._expert_quant.get(name, {}) + scheme = config.get("weight_transform") + if scheme not in ("nvfp4_nearest", "mxfp8_nearest"): + raise ValueError(f"Inkling2: {name}: missing or unsupported hf_quant_config.json scheme {scheme!r}") + nvfp4 = scheme == "nvfp4_nearest" + if nvfp4 and config.get("weight_scale_format") != "amax_denominator": + raise ValueError(f"Inkling2: {name}: expected NVFP4 amax_denominator scale format") + required = companions if nvfp4 else companions[:1] + for companion in required: + if companion not in self.model_tensors: + raise ValueError(f"Inkling2: {name}: missing companion {companion}") + if not nvfp4 and any(n in self.model_tensors for n in companions[1:]): + raise ValueError(f"Inkling2: {name}: MXFP8 must not have amax or outer_scale_denominator") + scale = self.model_tensors[companions[0]] + scale_tensor = scale() + weight_dtype, scale_dtype = (torch.uint8, torch.float8_e4m3fn) if nvfp4 else (torch.float8_e4m3fn, torch.uint8) + if tensor.dtype != weight_dtype or scale_tensor.dtype != scale_dtype: + raise ValueError(f"Inkling2: {name}: expected {weight_dtype} weights and {scale_dtype} scales, got {tensor.dtype} and {scale_tensor.dtype}") + experts = self.hparams["n_routed_experts"] + hidden = self.hparams["hidden_size"] + inter = self.find_hparam(["moe_intermediate_size", "intermediate_size"]) + w13 = name.endswith(".w13_weight") + rows, cols = (2 * inter, hidden) if w13 else (hidden, inter) + shape = (experts, rows, cols) + if min(shape) <= 0 or cols % (16 if nvfp4 else 32) or tuple(tensor.shape) != (experts, rows, cols // (2 if nvfp4 else 1)): + raise ValueError(f"Inkling2: {name}: invalid packed shape {tuple(tensor.shape)} for logical shape {shape}") + ss = tuple(scale_tensor.shape) + if len(ss) != 3 or ss[0] != experts or min(ss) <= 0 or rows % ss[1] or cols % ss[2]: + raise ValueError(f"Inkling2: {name}_scale: shape {ss} does not divide logical shape {shape}") + block = (rows // ss[1], cols // ss[2]) + if block != (1, 16 if nvfp4 else 32): + raise ValueError(f"Inkling2: {name}_scale: unsupported stored block shape {block}") + if list(block) != config.get("weight_block_shape"): + logger.warning("Inkling2: %s: hf_quant_config.json weight_block_shape %s conflicts with stored weight/scale shapes %s/%s; using %s", name, config.get("weight_block_shape"), tuple(tensor.shape), ss, list(block)) + amax = denominator = None + if nvfp4: + amax, denominator = (self.model_tensors[n] for n in companions[1:]) + for companion, gen, expected in ((companions[1], amax, (experts,)), (companions[2], denominator, (1,))): + t = gen() + if t.dtype != torch.float32 or tuple(t.shape) != expected: + raise ValueError(f"Inkling2: {companion}: expected F32 {expected}, got {t.dtype} {tuple(t.shape)}") + chunks: list[Callable[[], np.ndarray]] = [] + for expert in range(experts): + for half in range(2 if w13 else 1): + for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS): + stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows) + # The same packed row slice selects the weight and its scale groups. + row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop) + chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice)) + self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32) + self.model_tensors[name] = lambda shape=shape: torch.empty(shape, dtype=torch.float32, device="meta") + for companion in required: + del self.model_tensors[companion] + for name, gen in self.model_tensors.items(): + t = gen() + if not t.dtype.is_floating_point or t.element_size() == 1 or name.endswith(("_weight_scale", "_weight_amax", "_weight_outer_scale_denominator")): + raise ValueError(f"Inkling2: unexpected packed tensor or orphan companion {name}") + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, gen = item + if any(p in name for p in ("visual.", "vision_tower.", "mtp.", "markov_head", "nextn_predict")): + return None + name = name.replace("model.language_model.", "model.").replace("model.llm.", "model.") + # the mapping table cannot shift a block index: attn_queries.{i} feeds block i + 1 + name = re.sub(r"attn_res\.attn_queries\.(\d+)", lambda m: f"layers.{int(m[1]) + 1}.attention_input.query", name) + # the table maps a module, not its bias: gate.weight is the router, gate.bias the score correction + name = name.replace("mlp.gate.bias", "mlp.gate.e_score_correction_bias") + return name, gen + + def get_vocab_base(self): + tokens, types, pre = super().get_vocab_base() + n = self.hparams["unpadded_vocab_size"] + return tokens[:n], types[:n], pre + + def set_vocab(self): + tokens, types, pre = self.get_vocab_base() + self.gguf_writer.add_tokenizer_model("gpt2") + self.gguf_writer.add_tokenizer_pre(pre) + self.gguf_writer.add_token_list(tokens) + self.gguf_writer.add_token_types(types) + special = gguf.SpecialVocab(self.dir_model, load_merges=True) + eos = self.hparams["eos_token_id"] + special.special_token_ids["eos"] = eos + special.special_token_ids["eot"] = eos + special.add_special_token["bos"] = False + special.add_to_gguf(self.gguf_writer) + + def set_gguf_parameters(self): + hp = self.hparams + hp["num_attention_heads"] = [hp.get("swa_num_attention_heads", hp["num_attention_heads"]) if s else hp["num_attention_heads"] for s in self.is_swa] + hp["num_key_value_heads"] = [hp.get("swa_num_key_value_heads", hp["num_key_value_heads"]) if s else hp["num_key_value_heads"] for s in self.is_swa] + for name in ("n_routed_experts", "num_experts_per_tok"): + if name not in hp: + raise KeyError(f"Inkling2: missing {name}") + super().set_gguf_parameters() + w = self.gguf_writer + w.add_vocab_size(hp["vocab_size"]) + w.add_vocab_size_unpadded(hp["unpadded_vocab_size"]) + w.add_expert_feed_forward_length(self.find_hparam(["moe_intermediate_size", "intermediate_size"])) + w.add_key_length_swa(hp.get("swa_head_dim", hp["head_dim"])) + w.add_value_length_swa(hp.get("swa_head_dim", hp["head_dim"])) + w.add_rope_dimension_count(0) + w.add_sliding_window(hp["sliding_window_size"]) + w.add_sliding_window_pattern(self.is_swa) + w.add_shortconv_l_cache(self.find_hparam(["conv_kernel_size", "sconv_kernel_size"])) + w.add_expert_weights_scale(hp["route_scale"]) + w.add_activation_situ_beta(hp["mlp_gate_softcap"]) + w.add_activation_situ_linear_beta(hp["mlp_up_softcap"]) + w.add_attn_res_block_size(hp["n_layers_per_attn_res_block"]) + w.add_final_logit_softcapping(hp["final_logit_softcapping"]) + w.add_relative_length(hp["d_rel"]) + w.add_relative_extent(hp["rel_extent"]) + w.add_qk_clip(hp["qk_l2_clip_threshold"]) + w.add_relative_clip(hp["rel_l2_clip_threshold"]) + w.add_log_scale_floor(hp["log_scaling_n_floor"]) + w.add_log_scale_alpha(hp["log_scaling_alpha"]) + + def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int) -> gguf.GGMLQuantizationType | bool: + if new_name.endswith(("_conv.weight", "_clip.weight", "_res_query.weight", "attn_rel_bias.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 in self._packed_experts: + target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj") + yield self.map_tensor_name(target, try_suffixes=()) + ".weight", cast("Tensor", self._packed_experts[name]) + return + if name.endswith(".w13_weight"): + shape = data_torch.shape + data_torch = data_torch.reshape(shape[0], shape[1] // 2, 2, shape[2]).transpose(1, 2).reshape(shape) + name = name.replace(".w13_weight", ".gate_up_proj") + name = name.replace(".w2_weight", ".down_proj") + for static, conv in ((".static_weight", ".conv1d.weight"), (".static_w", ".weight")): + if name.endswith(static): + data_torch = data_torch.flip(0).T.contiguous() + name = name.removesuffix(static) + conv + if name.endswith((".conv1d.weight", "sconv.weight")): + data_torch = data_torch.squeeze(1) if data_torch.ndim == 3 else data_torch + elif name.endswith(".rel_logits_proj.proj"): + data_torch = data_torch.T.contiguous() + # a name the table maps without a suffix is a bare parameter + new_name = self.tensor_map.get_name(name) + if new_name is not None: + suffix = ".bias" if name.endswith(".e_score_correction_bias") else ".weight" + yield new_name + suffix, data_torch + else: + yield from super().modify_tensors(data_torch, name, bid) + + +@ModelBase.register("Inkling2ForConditionalGeneration") +class Inkling2VisionModel(MmprojModel): + def get_vision_config(self): + config = self.global_config.get("vision_config") + if not config: + return None + config = dict(config) + config["patch_size"] = config.get("native_patch_size", config.get("patch_size", 20)) + config["spatial_merge_size"] = config.get("adapter_merge_size", config.get("spatial_merge_size", 2)) + config["intermediate_size"] = config.get("intermediate_size") or int(config["hidden_size"] * config.get("mlp_ratio", 4.0)) + config["image_size"] = config["posemb_grid_size"] * config["patch_size"] + if config.get("num_channels", 3) != 3 or config.get("hidden_act", "gelu") != "gelu": + raise ValueError("Inkling2 vision requires RGB patches and exact GELU") + return config + + def set_gguf_parameters(self): + self.preprocessor_config.setdefault("image_mean", [0.5, 0.5, 0.5]) + self.preprocessor_config.setdefault("image_std", [0.5, 0.5, 0.5]) + super().set_gguf_parameters() + config = self.hparams + rope = config.get("rope_parameters") or {"rope_type": "axial", "rope_theta": 10000.0} + if rope["rope_type"] != "axial" or rope["rope_theta"] != 10000.0: + raise ValueError("Inkling2 vision requires axial RoPE with theta 10000") + w = self.gguf_writer + w.add_clip_vision_projector_type(gguf.VisionProjectorType.INKLING2V) + w.add_vision_attention_layernorm_eps(config["layer_norm_eps"]) + w.add_vision_spatial_merge_size(config["spatial_merge_size"]) + + def dequant_model(self): + # vision tensors are BF16, only the text experts are quantized + return + + @classmethod + def filter_tensors(cls, item): + name, gen = item + if not name.startswith(("model.visual.", "model.vision_tower.")): + return None + return name, gen + + # mm.{bid} takes the projector layer index, the mapping table cannot derive it from these names + _projector_layers = {"model.visual.proj_in": 1, "model.visual.proj_out": 2, "model.vision_tower.merger.linear_1": 1, "model.vision_tower.merger.linear_2": 2} + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + module, _, suffix = name.rpartition(".") + if module in self._projector_layers: + yield self.format_tensor_name(gguf.MODEL_TENSOR.V_MMPROJ, self._projector_layers[module], "." + suffix), data_torch + return + # lay out the linear patch embedding (HWC patches) as a conv2d for build_inp() + if name.endswith(".patch_embedding.weight"): + ps = self.hparams["patch_size"] + data_torch = data_torch.reshape(data_torch.shape[0], ps, ps, 3).permute(0, 3, 1, 2) + # these are bare parameters, they have no .weight + if name.endswith(("position_embedding", ".lambda_1", ".lambda_2", ".gamma")): + name = name.removesuffix(".gamma") + ".weight" + yield from super().modify_tensors(data_torch, name, bid) diff --git a/conversion/kokoro.py b/conversion/kokoro.py new file mode 100644 index 000000000000..945eccdaa271 --- /dev/null +++ b/conversion/kokoro.py @@ -0,0 +1,419 @@ +from __future__ import annotations + +import importlib +import importlib.util +import json +import math +import re +from collections import Counter, defaultdict +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path +from typing import Any, Callable, Iterable + +import torch +from torch import Tensor + +from .base import ModelBase, TextModel, MmprojModel, gguf, logger + +# Kokoro (StyleTTS2 with an iSTFTNet decoder), https://huggingface.co/hexgrad/Kokoro-82M +# text model: the PL-BERT phoneme encoder (ALBERT), one token per phoneme character +# mmproj: bert_encoder, prosody predictor, text encoder, decoder and the voices +# the text to phonemes step is the "tts" chat template, its dictionaries come from the misaki and nltk python packages + +DEFAULT_VOICE = "af_heart" + +MODULE_PREFIX = { + "bert_encoder": "a.gen.bert_enc.", + "predictor": "a.gen.pred.", + "text_encoder": "a.gen.text.", + "decoder": "a.gen.dec.", +} + + +def _checkpoint(dir_model: Path) -> Path | None: + paths = sorted(dir_model.glob("kokoro-*.pth")) + return paths[0] if paths else None + + +def _is_kokoro_checkpoint(dir_model: Path) -> bool: + if _checkpoint(dir_model) is None or not (dir_model / "config.json").is_file(): + return False + with open(dir_model / "config.json", encoding="utf-8") as f: + config = json.load(f) + return "plbert" in config and "istftnet" in config and "vocab" in config + + +@ModelBase.register_hparams_loader(_is_kokoro_checkpoint) +def _load_kokoro_hparams(dir_model: Path) -> dict[str, Any]: + logger.info("gguf: detected Kokoro checkpoint") + with open(dir_model / "config.json", encoding="utf-8") as f: + config = json.load(f) + plbert = config["plbert"] + return { + "architectures": ["KokoroModel"], + "model_type": "kokoro", + "num_hidden_layers": plbert["num_hidden_layers"], + "hidden_size": plbert["hidden_size"], + "intermediate_size": plbert["intermediate_size"], + "num_attention_heads": plbert["num_attention_heads"], + "max_position_embeddings": plbert["max_position_embeddings"], + "vocab_size": config["n_token"], + "layer_norm_eps": 1e-12, # AlbertConfig default + "kokoro": config, + # the mmproj tensors are named explicitly, they do not go through the block tensor map + "audio_config": {"num_hidden_layers": 0}, + } + + +def _load_modules(dir_model: Path, modules: Iterable[str]) -> dict[str, dict[str, Tensor]]: + path = _checkpoint(dir_model) + assert path is not None + state = torch.load(path, map_location="cpu", mmap=True, weights_only=True) + # every module was saved from a DataParallel wrapper + return {m: {k.removeprefix("module."): v for k, v in state[m].items()} for m in modules} + + +def _g2p_fallback(lexicons: list[dict[str, Any]]) -> dict[str, Any]: + # model for the words missing from the lexicon: n-grams over units "letter:sounds", learned from the lexicon + # key "<0 to 4 units before> " -> {sounds: probability}; "" pads the start of a word, the letter "$" is its end + # the "tts" template decodes it with a beam search + order, min_count, stress = 5, 3, "\u02c8\u02cc" + vowels = set("AIOQWYaiu\u00e6\u0251\u0252\u0254\u0259\u025b\u025c\u026a\u028a\u028c\u1d7b\u1d4a") + + def sounds(ps: str) -> list[str]: + # a stress mark goes with the sound after it, a length mark with the one before + out: list[str] = [] + pre = "" + for c in ps: + if c in stress: + pre += c + elif c == "\u02d0" and out: + out[-1] += c + else: + out.append(pre + c) + pre = "" + return out + + def penalty(letter: str, chunk: str) -> float: + # a consonant letter says consonants only; a vowel letter says a vowel, with at most a glide + flat = [c for c in chunk if c not in stress and c != "\u02d0"] + n_vowel = sum(c in vowels for c in flat) + if letter in "bcdfgjkmnpqstvxz" and n_vowel > 0: + return -8.0 + if letter in "aeiou" and flat and (n_vowel == 0 or any(c not in vowels and c not in "jw" for c in flat)): + return -8.0 + return 0.0 + + words: dict[str, list[str]] = {} + for lexicon in lexicons: + for word, v in lexicon.items(): + ps = v["DEFAULT"] if isinstance(v, dict) else v + # same spelling normalization as the template: doubled consonants and "ck" say one sound + w = re.sub(r"([b-df-hj-np-tv-z])\1", r"\1", word.lower()).replace("ck", "k") + if ps and " " not in ps and len(w) >= 2 and re.fullmatch(r"[a-z']+", w) and w not in words: + t = sounds(ps) + if len(t) <= 2 * len(w): + words[w] = t + + def align(w: str, t: list[str], cost: dict[str, dict[str, float]]) -> list[str] | None: + # best split of the sounds over the letters, each letter takes 0, 1 or 2 of them + n_l, n_t = len(w), len(t) + two = [t[j] + t[j + 1] for j in range(n_t - 1)] + best = [[-1e18] * (n_t + 1) for _ in range(n_l + 1)] + back = [[0] * (n_t + 1) for _ in range(n_l + 1)] + best[0][0] = 0.0 + for i in range(n_l): + letter = w[i] + row = cost.setdefault(letter, {}) + cur, nxt, bk = best[i], best[i + 1], back[i + 1] + # the sounds left must fit in the letters left + for j in range(max(0, n_t - 2 * (n_l - i)), n_t + 1): + base = cur[j] + if base < -1e17: + continue + for k, chunk in ((0, ""), (1, t[j] if j < n_t else None), (2, two[j] if j + 1 < n_t else None)): + if chunk is None: + break + c = row.get(chunk) + if c is None: + # not seen yet for this letter + c = row[chunk] = -12.0 + penalty(letter, chunk) + if base + c > nxt[j + k]: + nxt[j + k] = base + c + bk[j + k] = k + if best[n_l][n_t] < -1e17: + return None + out: list[str] = [] + j = n_t + for i in range(n_l, 0, -1): + k = back[i][j] + out.append("".join(t[j - k:j])) + j -= k + return out[::-1] + + # hard EM: align with the current letter -> sounds costs, count, repeat + # the costs are learned on a sample of the words, then every word is aligned once + def step(items: Iterable[tuple[str, list[str]]], cost: dict[str, dict[str, float]]) -> list[tuple[str, list[str]]]: + return [(w, a) for w, a in ((w, align(w, t, cost)) for w, t in items) if a is not None] + + sample = list(words.items())[::max(1, len(words) // 20000)] + cost: dict[str, dict[str, float]] = {} + for _ in range(5): + counts: dict[str, Counter[str]] = defaultdict(Counter) + for w, a in step(sample, cost): + for c, o in zip(w, a): + counts[c][o] += 1 + # small cost for a silent letter, so that a sound stays on its own letter + cost = {c: {o: math.log(n / sum(cnt.values())) - (0.5 if o == "" else 0.0) + penalty(c, o) for o, n in cnt.items()} + for c, cnt in counts.items()} + aligned = step(words.items(), cost) + + # counts of a unit after each of its contexts, from 4 units down to none + ngram: dict[str, Counter[str]] = defaultdict(Counter) + n_ctx: Counter[str] = Counter() + for w, a in aligned: + units = [""] * (order - 1) + [c + ":" + o for c, o in zip(w, a)] + ["$:"] + for i in range(order - 1, len(units)): + letter, _, o = units[i].partition(":") + for n in range(order): + ctx = " ".join(units[i - n:i]) + ngram[(ctx + " " if ctx else "") + letter][o] += 1 + n_ctx[ctx] += 1 + + # the probability is over all the units after the context, not only the ones of this letter + # this tells the search how likely the letter is after the sounds it chose, so it can drop a bad choice + model: dict[str, Any] = {} + for key, cnt in ngram.items(): + ctx, _, letter = key.rpartition(" ") + # the two shortest contexts keep all the readings that the letter has min_count times or more + kept = {o: float(f"{n / n_ctx[ctx]:.4g}") for o, n in cnt.most_common() + if n >= min_count or (key.count(" ") < 2 and ngram[letter][o] >= min_count)} + if kept: + model[key] = kept + return model + + +def _g2p_dicts() -> dict[str, dict[str, Any]] | None: + # dictionaries of the "tts" template: the misaki lexicon and the nltk averaged perceptron tagger + spec = importlib.util.find_spec("misaki") + if spec is None or spec.origin is None: + logger.warning("misaki is not installed, the model will take phonemes as prompt (pip install misaki nltk)") + return None + data = Path(spec.origin).parent / "data" + try: + nltk = importlib.import_module("nltk") + base = Path(str(nltk.data.find("taggers/averaged_perceptron_tagger_eng"))) / "averaged_perceptron_tagger_eng" + except (ImportError, LookupError): + logger.warning("the nltk tagger is not available, the model will take phonemes as prompt " + "(pip install nltk && python -m nltk.downloader averaged_perceptron_tagger_eng)") + return None + + def load(path: Path) -> Any: + with open(path, encoding="utf-8") as f: + return json.load(f) + + # tagger: classes sorted by label, feature -> {"c": weight} + # (index keys: jinja2's map(attribute=...) splits on "." and some labels are punctuation) + classes = sorted(load(Path(f"{base}.classes.json"))) + cid = {c: f"c{i}" for i, c in enumerate(classes)} + weights = load(Path(f"{base}.weights.json")) + lex = { + "gold": load(data / "us_gold.json"), + "silver": load(data / "us_silver.json"), + "gold_gb": load(data / "gb_gold.json"), + "silver_gb": load(data / "gb_silver.json"), + } + logger.info("gguf: learning the pronunciation of unknown words from the lexicon, this takes a few minutes") + # one process per variant + with ProcessPoolExecutor(max_workers=2) as pool: + lts, lts_gb = pool.map(_g2p_fallback, [[lex["gold"], lex["silver"]], [lex["gold_gb"], lex["silver_gb"]]]) + return { + **lex, + "lts": lts, + "lts_gb": lts_gb, + "pos_weights": {f: {cid[t]: w for t, w in tw.items()} for f, tw in weights.items()}, + "pos_tagdict": load(Path(f"{base}.tagdict.json")), + "pos_classes": {"": classes}, + } + + +@ModelBase.register("KokoroModel") +@ModelBase.example("hexgrad/Kokoro-82M") +class KokoroTextModel(TextModel): + model_arch = gguf.MODEL_ARCH.KOKORO + + _LAYER = "encoder.albert_layer_groups.0.albert_layers.0." + _TENSOR_MAP = { + "embeddings.LayerNorm": gguf.MODEL_TENSOR.TOKEN_EMBD_NORM, + "encoder.embedding_hidden_mapping_in": gguf.MODEL_TENSOR.TOKEN_EMBD_PROJ, + } + # the layers share their weights, stored as block 0 + _LAYER_TENSOR_MAP = { + "attention.query": gguf.MODEL_TENSOR.ATTN_Q, + "attention.key": gguf.MODEL_TENSOR.ATTN_K, + "attention.value": gguf.MODEL_TENSOR.ATTN_V, + "attention.dense": gguf.MODEL_TENSOR.ATTN_OUT, + "attention.LayerNorm": gguf.MODEL_TENSOR.ATTN_OUT_NORM, + "ffn": gguf.MODEL_TENSOR.FFN_UP, + "ffn_output": gguf.MODEL_TENSOR.FFN_DOWN, + "full_layer_layer_norm": gguf.MODEL_TENSOR.LAYER_OUT_NORM, + } + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + del remote_hf_model_id + bert = _load_modules(self.dir_model, ["bert"])["bert"] + return {name: (lambda t=t: t) for name, t in bert.items()} + + def set_vocab(self): + config = self.hparams["kokoro"] + n_vocab = config["n_token"] + tokens: list[str] = [f"[UNUSED_{i}]" for i in range(n_vocab)] + toktypes = [gguf.TokenType.UNUSED] * n_vocab + for text, i in config["vocab"].items(): + tokens[i] = text + toktypes[i] = gguf.TokenType.NORMAL + # id 0 pads both ends of the phoneme sequence + tokens[0] = "" + toktypes[0] = gguf.TokenType.CONTROL + + # the phonemes are mapped to tokens one character at a time by the audio pipeline + 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([0.0] * n_vocab) + self.gguf_writer.add_token_types(toktypes) + self.gguf_writer.add_bos_token_id(0) + self.gguf_writer.add_eos_token_id(0) + self.gguf_writer.add_pad_token_id(0) + self.gguf_writer.add_add_bos_token(False) + self.gguf_writer.add_add_eos_token(False) + + dicts = _g2p_dicts() + if dicts is not None: + template_path = Path(__file__).parent.parent / "models" / "templates" / "hexgrad-Kokoro-82M-tts.jinja" + with open(template_path, encoding="utf-8") as f: + self.gguf_writer.add_chat_template([{"name": "tts", "template": f.read()}]) + self.gguf_writer.add_tts_dicts(dicts) + + def set_gguf_parameters(self): + super().set_gguf_parameters() + self.gguf_writer.add_causal_attention(False) + self.gguf_writer.add_pooling_type(gguf.PoolingType.NONE) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + del bid + n_embd = self.hparams["hidden_size"] + + if name == "embeddings.word_embeddings.weight": + # zero-pad the rows to n_embd, llama.cpp wants token and embedding inputs of the same width + data_torch = torch.nn.functional.pad(data_torch, (0, n_embd - data_torch.shape[1])) + yield (self.format_tensor_name(gguf.MODEL_TENSOR.TOKEN_EMBD), data_torch) + return + if name == "embeddings.position_embeddings.weight": + # every token has type 0, fold its embedding into the positions + type0 = self.model_tensors["embeddings.token_type_embeddings.weight"]()[0] + yield (self.format_tensor_name(gguf.MODEL_TENSOR.POS_EMBD), data_torch + type0) + return + if name.startswith(("embeddings.token_type_embeddings.", "pooler.")): + return + + key, suffix = name.rsplit(".", 1) + if key in self._TENSOR_MAP: + yield (self.format_tensor_name(self._TENSOR_MAP[key], suffix="." + suffix), data_torch) + return + if key.startswith(self._LAYER): + tensor = self._LAYER_TENSOR_MAP[key.removeprefix(self._LAYER)] + yield (self.format_tensor_name(tensor, 0, suffix="." + suffix), data_torch) + return + raise ValueError(f"unexpected tensor {name}") + + +@ModelBase.register("KokoroModel") +@ModelBase.example("hexgrad/Kokoro-82M") +class KokoroMmprojModel(MmprojModel): + has_vision_encoder = False + has_audio_encoder = False + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._wnorm_g: dict[str, Tensor] = {} + self._wnorm_v: dict[str, Tensor] = {} + self._lstm_bias: dict[str, Tensor] = {} + + def get_audio_config(self) -> dict[str, Any] | None: + return self.global_config.get("audio_config") + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + del remote_hf_model_id + tensors: dict[str, Callable[[], Tensor]] = {} + for module, state in _load_modules(self.dir_model, MODULE_PREFIX.keys()).items(): + for name, t in state.items(): + tensors[MODULE_PREFIX[module] + name] = (lambda t=t: t) + return tensors + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + # the names are final already + return item + + def set_gguf_parameters(self): + config = self.global_config["kokoro"] + self.gguf_writer.add_file_type(self.ftype) + self.gguf_writer.add_clip_has_gen_audio_encoder(True) + self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.KOKORO) + self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_gen_audio_embedding_length(config["hidden_dim"]) + self.gguf_writer.add_gen_audio_feed_forward_length(config["hidden_dim"]) + self.gguf_writer.add_gen_audio_block_count(config["n_layer"]) + self.gguf_writer.add_gen_audio_head_count(1) + self.gguf_writer.add_gen_audio_attention_layernorm_eps(1e-5) + if (self.dir_model / "voices" / f"{DEFAULT_VOICE}.pt").is_file(): + self.gguf_writer.add_gen_audio_default_voice(DEFAULT_VOICE) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + del bid + # torch weight_norm: weight = g * v / |v| over dims 1..n + if name.endswith((".weight_g", ".weight_v")): + base = name[:-len(".weight_g")] + (self._wnorm_g if name.endswith("_g") else self._wnorm_v)[base] = data_torch + if base in self._wnorm_g and base in self._wnorm_v: + g = self._wnorm_g.pop(base).float() + v = self._wnorm_v.pop(base).float() + w = g * v / v.norm(dim=tuple(range(1, v.dim())), keepdim=True) + if base.endswith(".pool"): + # depthwise transposed conv [C, 1, 3], stored as one row per tap + w = w.squeeze(1).T.contiguous() + yield (base + ".weight", w) + return + # the two LSTM biases are always added + if ".bias_ih_l0" in name or ".bias_hh_l0" in name: + base = name.replace(".bias_ih_l0", ".bias_l0").replace(".bias_hh_l0", ".bias_l0") + if base in self._lstm_bias: + yield (base, self._lstm_bias.pop(base).float() + data_torch.float()) + else: + self._lstm_bias[base] = data_torch + return + # snake alphas are per channel + if ".alpha1." in name or ".alpha2." in name: + data_torch = data_torch.reshape(-1) + yield (name, data_torch) + + def tensor_force_quant(self, name, new_name, bid, n_dims): + del name, bid + # tensors read on the host stay F32 + if "lstm" in new_name or ".shared." in new_name or new_name.startswith(("a.gen.bert_enc.", "voice.")) \ + or ".duration_proj." in new_name or ".m_source." in new_name or ".pool." in new_name: + return gguf.GGMLQuantizationType.F32 + # CONV_TRANSPOSE_1D takes only F32 weights on some backends + if ".ups." in new_name: + return gguf.GGMLQuantizationType.F32 + # the conv ops have no BF16 kernels + if n_dims >= 2: + return gguf.GGMLQuantizationType.F16 + return gguf.GGMLQuantizationType.F32 + + def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: + # a voice is a table of style vectors, the row is picked by the number of phonemes + for path in sorted((self.dir_model / "voices").glob("*.pt")): + pack = torch.load(path, map_location="cpu", weights_only=True) + yield (f"voice.{path.stem}", pack.squeeze(1).float()) diff --git a/conversion/minimax.py b/conversion/minimax.py index 4d856fab855f..c9f512f5fa6f 100644 --- a/conversion/minimax.py +++ b/conversion/minimax.py @@ -1,5 +1,7 @@ from __future__ import annotations +import json + from typing import Iterable, Sequence, TYPE_CHECKING import torch @@ -8,6 +10,7 @@ from torch import Tensor from .base import ModelBase, TextModel, MmprojModel, gguf, logger +from .qwen import DSparkModel @ModelBase.register("MiniMaxText01ForCausalLM") @@ -170,6 +173,15 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None): class MiniMaxM3Model(MiniMaxM2Model): model_arch = gguf.MODEL_ARCH.MINIMAXM3 + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + # transformers 5.x folds sparse_attention_config and moe_layer_freq into other keys + with open(self.dir_model / "config.json", "r", encoding="utf-8") as f: + raw_hparams = json.load(f) + for key, value in raw_hparams.get("text_config", raw_hparams).items(): + self.hparams.setdefault(key, value) + def tensor_force_quant(self, name, new_name, bid, n_dims): if ".indexer." in new_name: return gguf.GGMLQuantizationType.F32 @@ -188,6 +200,7 @@ def set_gguf_parameters(self): self.gguf_writer.add_indexer_top_k(sac["sparse_topk_blocks"]) self.gguf_writer.add_indexer_block_size(sac["sparse_block_size"]) self.gguf_writer.add_indexer_local_blocks(sac["sparse_local_block"]) + self.gguf_writer.add_indexer_types([bool(v) for v in sac["sparse_attention_freq"]]) moe_layer_freq = self.find_hparam(["moe_layer_freq"]) n_dense = 0 @@ -201,7 +214,47 @@ def set_gguf_parameters(self): def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None): # Gemma-style (1 + w) RMSNorm: bake the +1 in so llama.cpp can use plain RMSNorm if name.endswith("norm.weight"): - data_torch = data_torch + 1.0 + data_torch = data_torch.float() + 1.0 + + yield from super().modify_tensors(data_torch, name, bid) + + +@ModelBase.register("DSparkMiniMaxDraftModel") +class MiniMaxM3DSparkModel(DSparkModel): + model_arch = gguf.MODEL_ARCH.DFLASH + + def __init__(self, dir_model, *args, **kwargs): + # transformers drops the draft keys when it parses the minimax_m3_vl config + with open(dir_model / "config.json", "r", encoding="utf-8") as f: + kwargs["hparams"] = json.load(f) + super().__init__(dir_model, *args, **kwargs) + + # draft layers use a dense FFN, the MoE keys are copied from the target config + self.hparams["intermediate_size"] = self.hparams["dspark_ffn_hidden_size"] + for key in ("num_local_experts", "num_experts_per_tok", "scoring_func"): + self.hparams.pop(key, None) + + def set_gguf_parameters(self): + super().set_gguf_parameters() + + self.gguf_writer.add_hidden_act(self.hparams["hidden_act"]) + + layer_types = self.hparams["layer_types"] + self.gguf_writer.add_sliding_window(self.hparams["sliding_window"]) + self.gguf_writer.add_sliding_window_pattern([t == "sliding_attention" for t in layer_types]) + + @classmethod + def filter_tensors(cls, item): + name, gen = item + name = name.removeprefix("language_model.model.dspark.").replace(".decoder_layer.", ".") + if name == "final_norm.weight": + name = "norm.weight" + return super().filter_tensors((name, gen)) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None): + # Gemma-style (1 + w) RMSNorm, same as the target + if name.endswith("norm.weight"): + data_torch = data_torch.float() + 1.0 yield from super().modify_tensors(data_torch, name, bid) diff --git a/conversion/minimax_music3.py b/conversion/minimax_music3.py new file mode 100644 index 000000000000..2fbba8fab4a8 --- /dev/null +++ b/conversion/minimax_music3.py @@ -0,0 +1,285 @@ +from __future__ import annotations + +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, gguf +from .drama3 import fold_snake +from .qwen import Qwen3Model + +# MiniMax Music 3, diffusers layout: one checkpoint per component +# text model: the global LLM (language_model/), samples the semantic code of each frame +# mmproj: RVQ depth decoder, condition encoder, flow-matching DiT and DAC decoder (vocoder) + +LM_DIR = "language_model" +TOK_DIR = "tokenizer" +MMPROJ_DIRS = ("rvq_depth_decoder", "condition_encoder", "transformer", "vocoder") + +# token ids of the checkpoint, see encoders.py of the diffusers pipeline +AUDIO_START = 151669 +AUDIO_END = 151670 +AUDIO_CODE_OFFSET = 151675 +N_SEMANTIC = 16384 + + +def _load_hparams(dir_model: Path) -> dict[str, Any]: + return ModelBase.load_hparams(dir_model / LM_DIR, is_mistral_format=False) + + +def _index_dirs(model: ModelBase, dirs: Iterable[str], keep: Callable[[str], bool]) -> dict[str, Callable[[], Tensor]]: + # the names get the component dir as prefix + root = model.dir_model + tensors: dict[str, Callable[[], Tensor]] = {} + try: + for d in dirs: + model.dir_model = root / d + prefix = "model" if d == LM_DIR else "diffusion_pytorch_model" + for name, gen in model.index_local_tensors(prefix).items(): + if keep(f"{d}.{name}"): + tensors[f"{d}.{name}"] = gen + finally: + model.dir_model = root + return tensors + + +def _fold_wn(g: Tensor, v: Tensor) -> Tensor: + # torch weight norm, over every dim but 0 + g, v = g.float(), v.float() + return g * v / v.flatten(1).norm(dim=1).view(-1, *[1] * (v.dim() - 1)) + + +@ModelBase.register("MiniMaxMusic3ForConditionalGeneration") +class MiniMaxMusic3TextModel(Qwen3Model): + model_arch = gguf.MODEL_ARCH.QWEN3 + + def __init__(self, dir_model: Path, *args, **kwargs): + kwargs.pop("hparams", None) + super().__init__(dir_model, *args, hparams=_load_hparams(dir_model), **kwargs) + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + tensors = _index_dirs(self, [LM_DIR], lambda _: True) + return {name.removeprefix(LM_DIR + "."): gen for name, gen in tensors.items()} + + def set_gguf_parameters(self): + super().set_gguf_parameters() + # the codes are sampled with classifier-free guidance, the uncond prompt runs as a second sequence + self.gguf_writer.add_classifier_free_guidance(True) + + def set_vocab(self): + root = self.dir_model + self.dir_model = root / TOK_DIR + try: + tokens, toktypes, tokpre = self.get_vocab_base() + special_vocab = gguf.SpecialVocab(self.dir_model, load_merges=True) + finally: + self.dir_model = root + + # the semantic codes are not in the tokenizer, name them for debugging + for i in range(N_SEMANTIC): + tokens[AUDIO_CODE_OFFSET + i] = f"<|audio_code_{i}|>" + toktypes[AUDIO_CODE_OFFSET + i] = gguf.TokenType.CONTROL + + # the generation ends with <|audio_end|>, the chat template of the tokenizer is not used + template_path = Path(__file__).parent.parent / "models" / "templates" / "MiniMaxAI-MiniMax-Music3-tts.jinja" + with open(template_path, encoding="utf-8") as f: + special_vocab.chat_template = [{"name": "tts", "template": f.read()}] + special_vocab.special_token_ids["eos"] = AUDIO_END + + self.gguf_writer.add_tokenizer_model("gpt2") + self.gguf_writer.add_tokenizer_pre(tokpre) + self.gguf_writer.add_token_list(tokens) + self.gguf_writer.add_token_types(toktypes) + special_vocab.add_to_gguf(self.gguf_writer) + + +@ModelBase.register("MiniMaxMusic3ForConditionalGeneration") +class MiniMaxMusic3MmprojModel(MmprojModel): + has_vision_encoder = False + has_audio_encoder = False + + def __init__(self, dir_model: Path, *args, **kwargs): + kwargs.pop("hparams", None) + hparams = ModelBase.load_hparams(dir_model, is_mistral_format=False) + hparams["text_config"] = _load_hparams(dir_model) + for d in MMPROJ_DIRS: + hparams[d] = ModelBase.load_hparams(dir_model / d, is_mistral_format=False) + super().__init__(dir_model, *args, hparams=hparams, **kwargs) + + def get_audio_config(self) -> dict[str, Any] | None: + # the generic gen layers are the depth decoder + return self.global_config["rvq_depth_decoder"] + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + # from the backbone, only the embeddings of the semantic codes + return _index_dirs(self, (LM_DIR, *MMPROJ_DIRS), + lambda name: not name.startswith(LM_DIR + ".") or name == f"{LM_DIR}.model.embed_tokens.weight") + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + return item + + def set_gguf_parameters(self): + hp = self.hparams + self.gguf_writer.add_file_type(self.ftype) + self.gguf_writer.add_clip_has_gen_audio_encoder(True) + self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.MINIMAX_MUSIC3_GEN) + self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_gen_audio_embedding_length(hp["hidden_size"]) + self.gguf_writer.add_gen_audio_feed_forward_length(hp["intermediate_size"]) + self.gguf_writer.add_gen_audio_block_count(hp["num_layers"]) + self.gguf_writer.add_gen_audio_head_count(hp["num_attention_heads"]) + self.gguf_writer.add_gen_audio_attention_layernorm_eps(1e-6) + # the DiT, the condition encoder and the vocoder hparams come from the tensor shapes or are hard-coded in tools/mtmd + + def tensor_force_quant(self, name, new_name, bid, n_dims): + # only the transformer layers follow --outtype, the convs and the small projections stay F32 + if n_dims >= 2 and new_name.startswith(("a.gen.code.blk.", "a.gen.flow.blk.")): + return super().tensor_force_quant(name, new_name, bid, n_dims) + if new_name.startswith(("a.gen.code.head", "a.gen.code.embd", "a.gen.code.out_embd", "a.gen.code.proj_in")): + return super().tensor_force_quant(name, new_name, bid, n_dims) + return gguf.GGMLQuantizationType.F32 + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + if name.startswith("a."): + yield (name, data_torch) + return + + comp, key = name.split(".", 1) + if comp == LM_DIR: + yield ("a.gen.code.out_embd.weight", data_torch[AUDIO_CODE_OFFSET:AUDIO_CODE_OFFSET + N_SEMANTIC]) + elif comp == "rvq_depth_decoder": + yield from self._depth(data_torch, key) + elif comp == "condition_encoder": + yield from self._cond(data_torch, key) + elif comp == "transformer": + yield from self._dit(data_torch, key) + # the vocoder is folded in generate_extra_tensors() + + def _depth(self, t: Tensor, key: str) -> Iterable[tuple[str, Tensor]]: + p = "a.gen.code" + n_cb = self.hparams["num_codebooks"] - 1 + if key == "audio_embeddings.weight": + # one table per residual codebook + yield (f"{p}.embd.weight", t.reshape(n_cb, -1, t.shape[-1])) + elif key.startswith("audio_heads."): + if key == "audio_heads.0.weight": + heads = [self._tensor(f"rvq_depth_decoder.audio_heads.{i}.weight") for i in range(n_cb)] + yield (f"{p}.head.weight", torch.stack(heads)) + elif key == "projection.weight": + yield (f"{p}.proj_in.weight", t) + elif key == "pos_embedding.weight": + yield (f"{p}.position_embd.weight", t) + elif key == "norm.weight": + yield (f"{p}.post_ln.weight", t) + else: + _, il, rest = key.split(".", 2) + layer = { + "input_layernorm.weight": "ln1.weight", + "attn.to_q.weight": "attn_q.weight", + "attn.to_k.weight": "attn_k.weight", + "attn.to_v.weight": "attn_v.weight", + "attn.to_out.weight": "attn_out.weight", + "post_attention_layernorm.weight": "ln2.weight", + "gate_proj.weight": "ffn_gate.weight", + "up_proj.weight": "ffn_up.weight", + "down_proj.weight": "ffn_down.weight", + } + yield (f"{p}.blk.{il}.{layer[rest]}", t) + + def _cond(self, t: Tensor, key: str) -> Iterable[tuple[str, Tensor]]: + p = "a.gen.cond" + if key == "layer_weight_logits": + # softmax mix of the 8 hidden states of a frame, with the scale folded in + scale = self._tensor("condition_encoder.layer_scale").float() + yield (f"{p}.layer_w", torch.softmax(t.float(), dim=0) * scale) + elif key == "proj.weight": + yield (f"{p}.proj.weight", t) + elif key == "proj.bias": + yield (f"{p}.proj.bias", t) + + def _dit(self, t: Tensor, key: str) -> Iterable[tuple[str, Tensor]]: + p = "a.gen.flow" + if key.startswith("transformer_blocks."): + _, il, rest = key.split(".", 2) + q = f"{p}.blk.{il}" + if rest.startswith("ff_in."): + # value half first, then the silu gate half + suffix = rest.removeprefix("ff_in.") + up, gate = t.chunk(2, dim=0) + yield (f"{q}.ffn_up.{suffix}", up) + yield (f"{q}.ffn_gate.{suffix}", gate) + return + layer = { + "norm1.weight": "ln1.weight", + "norm1.bias": "ln1.bias", + "attn.to_q.weight": "attn_q.weight", + "attn.to_k.weight": "attn_k.weight", + "attn.to_v.weight": "attn_v.weight", + "attn.to_out.0.weight": "attn_out.weight", + "norm2.weight": "ln2.weight", + "norm2.bias": "ln2.bias", + "ff_out.weight": "ffn_down.weight", + "ff_out.bias": "ffn_down.bias", + } + yield (f"{q}.{layer[rest]}", t) + return + if key == "time_proj.weight": + # random Fourier features, 2 * pi folded in + yield (f"{p}.time_freq", t.float().flatten() * 2.0 * torch.pi) + return + out = { + "time_embed.linear_1.weight": "time_in.weight", + "time_embed.linear_1.bias": "time_in.bias", + "time_embed.linear_2.weight": "time_out.weight", + "time_embed.linear_2.bias": "time_out.bias", + "preprocess_conv.weight": "pre.weight", + "proj_in.weight": "proj_in.weight", + "proj_out.weight": "proj_out.weight", + "postprocess_conv.weight": "post.weight", + }[key] + yield (f"{p}.{out}", t.squeeze(-1) if key.endswith("conv.weight") else t) + + def _tensor(self, name: str) -> Tensor: + # read directly, without the dtype handling of prepare_tensors() + return self.model_tensors[name]().float() + + def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: + # DAC decoder, same layout as the yue2 VAE (a.gen.vae.*), with the snake and the weight norm folded + def get(key: str) -> Tensor: + return self._tensor(f"vocoder.{key}") + + def wn(key: str) -> Tensor: + return _fold_wn(get(key + ".weight_g"), get(key + ".weight_v")) + + def snake(dst: str, key: str) -> Iterable[tuple[str, Tensor]]: + a, b = fold_snake(get(key + ".alpha")) + yield (f"{dst}.alpha", a) + yield (f"{dst}.beta", b) + + p = "a.gen.vae" + yield (f"{p}.in_proj.weight", get("dec_in_proj.weight")) + yield (f"{p}.in_proj.bias", get("dec_in_proj.bias")) + yield (f"{p}.conv_in.weight", wn("conv_in")) + yield (f"{p}.conv_in.bias", get("conv_in.bias")) + n_blk = len(self.global_config["vocoder"]["upsampling_ratios"]) + for b in range(n_blk): + s = f"blocks.{b}" + yield from snake(f"{p}.blk.{b}.snake", f"{s}.snake1") + yield (f"{p}.blk.{b}.up.weight", wn(f"{s}.conv_t1")) + yield (f"{p}.blk.{b}.up.bias", get(f"{s}.conv_t1.bias")) + for r in range(3): + rs = f"{s}.res_unit{r + 1}" + yield from snake(f"{p}.blk.{b}.res.{r}.snake1", f"{rs}.snake1") + yield (f"{p}.blk.{b}.res.{r}.conv1.weight", wn(f"{rs}.conv1")) + yield (f"{p}.blk.{b}.res.{r}.conv1.bias", get(f"{rs}.conv1.bias")) + yield from snake(f"{p}.blk.{b}.res.{r}.snake2", f"{rs}.snake2") + yield (f"{p}.blk.{b}.res.{r}.conv2.weight", wn(f"{rs}.conv2")) + yield (f"{p}.blk.{b}.res.{r}.conv2.bias", get(f"{rs}.conv2.bias")) + yield from snake(f"{p}.post_snake", "snake_out") + yield (f"{p}.conv_out.weight", wn("conv_out")) + yield (f"{p}.conv_out.bias", get("conv_out.bias")) diff --git a/conversion/pplx_decider.py b/conversion/pplx_decider.py index b71bd8a3ad23..6507d29faecb 100644 --- a/conversion/pplx_decider.py +++ b/conversion/pplx_decider.py @@ -18,9 +18,12 @@ def _is_pplx_decider_checkpoint(dir_model: Path) -> bool: if not all((dir_model / name).is_file() for name in ("decision_config.json", "readout.safetensors", "config.json")): return False + with open(dir_model / "config.json", encoding="utf-8") as f: + config = json.load(f) with open(dir_model / "decision_config.json", encoding="utf-8") as f: - # the same layout with a format_id is a vllm-d3 checkpoint - return "format_id" not in json.load(f) + decision = json.load(f) + # pplx-decider is a Qwen3.5 backbone, and a format_id means vllm-d3 + return config.get("model_type") in ("qwen3_5", "qwen3_5_text") and "format_id" not in decision @ModelBase.register_hparams_loader(_is_pplx_decider_checkpoint) diff --git a/conversion/qwen3tts.py b/conversion/qwen3tts.py index 28bb6e095f56..1ea14692bc4c 100644 --- a/conversion/qwen3tts.py +++ b/conversion/qwen3tts.py @@ -275,6 +275,14 @@ def tensor_force_quant(self, name, new_name, bid, n_dims): or (".dac.blk." in new_name and (new_name.endswith(".conv1.weight") or new_name.endswith(".conv2.weight"))) ): return gguf.GGMLQuantizationType.F16 + # the reference encoder's convs run with an F32 im2col, see f32_im2col in pockettts-seanet.cpp + if new_name.startswith("a.seanet.") or new_name == "a.downsample.conv.weight": + return gguf.GGMLQuantizationType.F32 + # codes are picked by the nearest codebook entry: Q8_0 changes about 8% of them, F16 none + if new_name.startswith("a.gen.enc.tfm.blk.") and new_name.endswith(".weight") and n_dims == 2: + return gguf.GGMLQuantizationType.F16 + if new_name.startswith("a.gen.enc.quant."): + return gguf.GGMLQuantizationType.F32 # ConvTranspose1d kernels: only F16/F32 are implemented, no BF16 if new_name.endswith(".conv.weight") and (".up.blk." in new_name or ".dac.blk." in new_name): return gguf.GGMLQuantizationType.F32 @@ -298,8 +306,8 @@ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Ca return super().filter_tensors((name, gen)) def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: - # code2wav tensors are already named by generate_extra_tensors(), pass them through - if name.startswith("a.gen.wav."): + # code2wav and reference encoder tensors are already named by generate_extra_tensors(), pass them through + if name.startswith(("a.gen.wav.", "a.gen.enc.", "a.seanet.", "a.downsample.")): yield (name, data_torch) return @@ -356,6 +364,68 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: yield from self._generate_code2wav_tensors() + yield from self._generate_ref_encoder_tensors() + + # mimi encoder of the speech tokenizer: reference clip -> codes, for voice cloning with a transcript (ICL) + def _generate_ref_encoder_tensors(self) -> Iterable[tuple[str, Tensor]]: + from safetensors.torch import load_file + + state_dict = load_file(self.dir_model / "speech_tokenizer" / "model.safetensors") + if "encoder.downsample.conv.weight" not in state_dict: + return + + with open(self.dir_model / "speech_tokenizer" / "config.json", "r", encoding="utf-8") as f: + enc_config = json.load(f)["encoder_config"] + n_stage = len(enc_config["upsampling_ratios"]) + + T = gguf.MODEL_TENSOR + + # encoder.encoder.layers: conv_in, then per stage a residual unit, an ELU and a strided conv, then an ELU and conv_out + def seanet(idx: int, suffix: str) -> Tensor: + return state_dict[f"encoder.encoder.layers.{idx}.{suffix}"] + + for suffix in ("weight", "bias"): + yield (self.format_tensor_name(T.A_ENC_SEANET_CONV_IN, suffix=f".{suffix}"), seanet(0, f"conv.{suffix}")) + yield (self.format_tensor_name(T.A_ENC_SEANET_CONV_OUT, suffix=f".{suffix}"), seanet(3 * n_stage + 2, f"conv.{suffix}")) + for stage in range(n_stage): + yield (self.format_tensor_name(T.A_ENC_SEANET_RES_CONV1, stage, suffix=f".{suffix}"), seanet(3 * stage + 1, f"block.1.conv.{suffix}")) + yield (self.format_tensor_name(T.A_ENC_SEANET_RES_CONV2, stage, suffix=f".{suffix}"), seanet(3 * stage + 1, f"block.3.conv.{suffix}")) + yield (self.format_tensor_name(T.A_ENC_SEANET_SCALE_CONV, stage, suffix=f".{suffix}"), seanet(3 * stage + 3, f"conv.{suffix}")) + + yield (self.format_tensor_name(T.A_ENC_DOWNSAMPLE_CONV), state_dict["encoder.downsample.conv.weight"]) + + tfm_layer_map = { + "input_layernorm.weight": (T.A_GEN_ENC_TFM_ATTN_NORM, ".weight"), + "input_layernorm.bias": (T.A_GEN_ENC_TFM_ATTN_NORM, ".bias"), + "self_attn.q_proj.weight": (T.A_GEN_ENC_TFM_ATTN_Q, ".weight"), + "self_attn.k_proj.weight": (T.A_GEN_ENC_TFM_ATTN_K, ".weight"), + "self_attn.v_proj.weight": (T.A_GEN_ENC_TFM_ATTN_V, ".weight"), + "self_attn.o_proj.weight": (T.A_GEN_ENC_TFM_ATTN_OUT, ".weight"), + "self_attn_layer_scale.scale": (T.A_GEN_ENC_TFM_ATTN_SCALE, ".weight"), + "post_attention_layernorm.weight": (T.A_GEN_ENC_TFM_FFN_NORM, ".weight"), + "post_attention_layernorm.bias": (T.A_GEN_ENC_TFM_FFN_NORM, ".bias"), + "mlp.fc1.weight": (T.A_GEN_ENC_TFM_FFN_UP, ".weight"), + "mlp.fc2.weight": (T.A_GEN_ENC_TFM_FFN_DOWN, ".weight"), + "mlp_layer_scale.scale": (T.A_GEN_ENC_TFM_FFN_SCALE, ".weight"), + } + for bid in range(enc_config["num_hidden_layers"]): + for key, (tensor_id, suffix) in tfm_layer_map.items(): + yield (self.format_tensor_name(tensor_id, bid, suffix=suffix), state_dict[f"encoder.encoder_transformer.layers.{bid}.{key}"]) + + def rvq_codebook(prefix: str, idx: int) -> Tensor: + # checkpoint has EMA accumulators, so codebook = embed_sum / cluster_usage + embed_sum = state_dict[f"{prefix}.layers.{idx}.codebook.embed_sum"] + cluster_usage = state_dict[f"{prefix}.layers.{idx}.codebook.cluster_usage"] + return embed_sum / cluster_usage.clamp_min(1e-5).unsqueeze(-1) + + # the tokenizer keeps the semantic codebook and the first acoustic ones, see encoder_valid_num_quantizers + semantic = "encoder.quantizer.semantic_residual_vector_quantizer" + acoustic = "encoder.quantizer.acoustic_residual_vector_quantizer" + yield (self.format_tensor_name(T.A_GEN_ENC_QUANT_FIRST_IN), state_dict[f"{semantic}.input_proj.weight"].squeeze(-1)) + yield (self.format_tensor_name(T.A_GEN_ENC_QUANT_FIRST_CB), rvq_codebook(semantic, 0)) + yield (self.format_tensor_name(T.A_GEN_ENC_QUANT_REST_IN), state_dict[f"{acoustic}.input_proj.weight"].squeeze(-1)) + yield (self.format_tensor_name(T.A_GEN_ENC_QUANT_REST_CB), + torch.stack([rvq_codebook(acoustic, i) for i in range(self._CODE_GEN_N_CODEBOOKS)], dim=0)) def _generate_code2wav_tensors(self) -> Iterable[tuple[str, Tensor]]: # code2wav weights live in speech_tokenizer/model.safetensors, not the main safetensors diff --git a/conversion/qwen4exp.py b/conversion/qwen4exp.py index 9680d2937dfb..fe49cc03d5f3 100644 --- a/conversion/qwen4exp.py +++ b/conversion/qwen4exp.py @@ -8,7 +8,7 @@ import gguf import numpy as np -from .base import ModelBase +from .base import LazyTorchTensor, ModelBase from .qwen import _LinearAttentionVReorderBase, _Qwen35MRopeMixin from .qwen3vl import Qwen3VLVisionModel @@ -41,6 +41,18 @@ def __init__(self, *args, **kwargs): self._ple_shards: dict[int, str] = {} self._ple_row_dim: int | None = None self._mtp_fc: dict[str, Tensor] = {} + self._ple_scale: float | None = None + + def dequant_model(self): + # FP8 checkpoints: all n-gram shards share one scale, stored under the parent module name + # there is no "ngram_embedding.weight", so the generic FP8 pass drops it or cannot map it + for name in list(self.model_tensors): + if name.endswith(".ngram_embedding.weight_scale"): + scale = LazyTorchTensor.to_eager(self.model_tensors.pop(name)()).float().flatten() + if scale.numel() != 1: + raise ValueError(f"PLE scale {name!r} must be a scalar, got {scale.numel()} values") + self._ple_scale = float(scale[0]) + super().dequant_model() @classmethod def filter_tensors(cls, item): @@ -203,21 +215,31 @@ def _place_ple_shard(self, data_torch: Tensor, name: str) -> Iterable[tuple[str, f"PLE shard {shard} has row dim {int(shape[-1])}, expected {self._ple_row_dim}") rows += int(shape[0]) + # an FP8 table keeps its bytes and gets a scale tensor, any other type has the scale folded in + keep_fp8 = name in self._fp8_e4m3_preserved table = gguf.LazyChunkedTensor( - [self._load_ple_shard(shard) for shard in shards], + [self._load_ple_shard(shard, keep_fp8) for shard in shards], shape=(rows, self._ple_row_dim), - dtype=np.float32, + dtype=np.uint8 if keep_fp8 else np.float32, ) gguf_name = gguf.TENSOR_NAMES[gguf.MODEL_TENSOR.PER_LAYER_TOKEN_EMBD] - return [(gguf_name + ".weight", cast(Tensor, table))] + out = [(gguf_name + ".weight", cast(Tensor, table))] + if keep_fp8 and self._ple_scale is not None: + out.append((gguf_name + ".scale", torch.tensor([self._ple_scale], dtype=torch.float32))) + return out - def _load_ple_shard(self, name: str): + def _load_ple_shard(self, name: str, keep_fp8: bool): def load() -> np.ndarray: - from .base import LazyTorchTensor - # a fresh lazy tensor every call, or to_eager() memoizes every shard eager = LazyTorchTensor.to_eager(self.model_tensors[name]()) - return eager.to(torch.float32).contiguous().numpy() + if keep_fp8: + if eager.dtype != torch.float8_e4m3fn: + raise ValueError(f"PLE shard {name} is {eager.dtype}, expected FP8 like the other shards") + return eager.contiguous().view(torch.uint8).numpy() + data = eager.to(torch.float32) + if self._ple_scale is not None: + data = data * self._ple_scale + return data.contiguous().numpy() return load def prepare_tensors(self): diff --git a/conversion/tiny_voca.py b/conversion/tiny_voca.py new file mode 100644 index 000000000000..6bfa5490732d --- /dev/null +++ b/conversion/tiny_voca.py @@ -0,0 +1,443 @@ +from __future__ import annotations + +import importlib.util +import json +import re +import unicodedata +from pathlib import Path +from typing import Any, Callable, Iterable + +import numpy as np +import torch +from torch import Tensor + +from .base import ModelBase, TextModel, MmprojModel, gguf, logger + +# tiny-voca, https://huggingface.co/n4ze3m/tiny-voca +# +# text model: phoneme encoder (4 blocks), the input rows are built by the audio pipeline (token + stress + voice) +# mmproj: input tables, voices, duration predictor, prosody and acoustic stacks, source-filter heads +# +# the text to phonemes step (dizione) is the "tts" chat template, see models/templates/n4ze3m-tiny-voca-tts.jinja +# its lexicon comes from the phonemizer/ directory of the model, the other tables from the dizione python package +# +# the prosody and acoustic stacks have the same blocks as the encoder, they are stored with the libllama names +# of the tiny-voca arch under a.gen.prosody. and a.gen.acoustic., mtmd runs them on llama contexts of its own + +CHECKPOINT = "tiny-voca.pt" +DEFAULT_VOICE = "M2" + +# phone classes of the reference (text.py): the phones get at least one frame, the vowels are always voiced +VOWELS = ("ə", "ɐ", "ɚ", "ᵻ", "ɪ", "i", "iː", "ɛ", "æ", "ʌ", "ɑː", "ɔ", "ɔː", "ʊ", "uː", "ɜː", + "eɪ", "aɪ", "ɔɪ", "oʊ", "aʊ", "iə", "oː", + "ɑːɹ", "ɔːɹ", "oːɹ", "ɪɹ", "ɛɹ", "ʊɹ", "aɪɚ", "aɪə", "əl", "n̩") +CONSONANTS = ("p", "b", "t", "d", "k", "ɡ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h", + "m", "n", "ŋ", "l", "ɹ", "j", "w", "tʃ", "dʒ", "ɾ", "ʔ") + +# input letters and output phonemes of the unknown-word model, fixed in mtmd (see mtmd_graph_tiny_voca) +G2P_LETTERS = "abcdefghijklmnopqrstuvwxyz'" +G2P_SYMBOLS = [v + d for v in ("AA", "AE", "AH", "AO", "AW", "AY") for d in "012"] + ["B", "CH", "D", "DH"] + \ + [v + d for v in ("EH", "ER", "EY") for d in "012"] + ["F", "G", "HH"] + [v + d for v in ("IH", "IY") for d in "012"] + \ + ["JH", "K", "L", "M", "N", "NG"] + [v + d for v in ("OW", "OY") for d in "012"] + ["P", "R", "S", "SH", "T", "TH"] + \ + [v + d for v in ("UH", "UW") for d in "012"] + ["V", "W", "Y", "Z", "ZH"] + +# block tensors: reference name -> libllama name +BLOCK_MAP = { + "norm1": "attn_norm", + "attention.qkv": "attn_qkv", + "attention.out": "attn_output", + "norm2": "ffn_norm", + "depthwise": "ssm_conv1d", + "expand": "ffn_up", + "project": "ffn_down", +} + +# mmproj stacks: reference module -> prefix +STACK_PREFIX = { + "prosody_stack": "a.gen.prosody.", + "acoustic_stack": "a.gen.acoustic.", +} + +# other mmproj tensors: reference module -> name +MMPROJ_MAP = { + "tokens": "a.gen.tok_embd", + "stress": "a.gen.stress_embd", + "duration.conv1": "a.gen.dur.conv1", + "duration.conv2": "a.gen.dur.conv2", + "duration.norm1": "a.gen.dur.norm1", + "duration.norm2": "a.gen.dur.norm2", + "duration.out": "a.gen.dur.out", + "frame_position": "a.gen.frame_pos", + "prosody_head": "a.gen.prosody_head", + "prosody_projection": "a.gen.prosody_proj", + "vocoder.harmonic": "a.gen.voc.harmonic", + "vocoder.noise": "a.gen.voc.noise", +} + + +def _is_tiny_voca_checkpoint(dir_model: Path) -> bool: + if not (dir_model / CHECKPOINT).is_file() or not (dir_model / "config.json").is_file(): + return False + with open(dir_model / "config.json", encoding="utf-8") as f: + config = json.load(f) + return config.get("phonemizer", {}).get("name") == "dizione" and "vocab" in config and "model" in config + + +@ModelBase.register_hparams_loader(_is_tiny_voca_checkpoint) +def _load_tiny_voca_hparams(dir_model: Path) -> dict[str, Any]: + logger.info("gguf: detected tiny-voca checkpoint") + with open(dir_model / "config.json", encoding="utf-8") as f: + config = json.load(f) + c = config["model"] + return { + "architectures": ["TinyVocaModel"], + "model_type": "tiny-voca", + "num_hidden_layers": c["encoder_layers"], + "hidden_size": c["channels"], + "intermediate_size": c["feedforward"], + "num_attention_heads": c["heads"], + "num_key_value_heads": c["heads"], + "max_position_embeddings": c["max_tokens"], + "vocab_size": c["vocab_size"], + "layer_norm_eps": 1e-5, # torch LayerNorm default + "rope_theta": 10000.0, + "tiny_voca": config, + # the mmproj tensors are named explicitly, they do not go through the block tensor map + "audio_config": {"num_hidden_layers": 0}, + } + + +def _table_rows(path: Path) -> Iterable[list[str]]: + # dizione tables: columns separated by tabs or two or more spaces, "#" comments + for line in path.read_text(encoding="utf-8").splitlines(): + line = line.split("#", 1)[0].rstrip() if line.lstrip().startswith("#") else line.rstrip() + if line.strip(): + yield [c.strip() for c in re.split(r"\t+| {2,}", line.strip())] + + +def _g2p_dicts(dir_model: Path) -> dict[str, dict[str, Any]] | None: + lexicon_path = dir_model / "phonemizer" / "lexicon.tsv" + spec = importlib.util.find_spec("dizione") + if not lexicon_path.is_file() or spec is None or spec.origin is None: + logger.warning("dizione or phonemizer/lexicon.tsv not found, the model will take phonemes as prompt " + "(pip install git+https://github.com/n4ze3m/dizione)") + return None + data = Path(spec.origin).parent / "data" + lexicon: dict[str, str] = {} + for line in lexicon_path.read_text(encoding="utf-8").splitlines(): + if "\t" in line: + word, phones = line.split("\t", 1) + lexicon[word] = phones.strip() + + # word -> [stress class, form, final form or ""], see function_words.txt + functions = {r[0]: [r[1], r[2], r[3] if len(r) > 3 else ""] for r in _table_rows(data / "function_words.txt")} + # words -> [class, forms (one, or one per word), final form or ""], see phrases.txt + phrases = {r[0]: [r[1], [f.strip() for f in r[2].split("|")], r[3] if len(r) > 3 else ""] for r in _table_rows(data / "phrases.txt")} + letters = {r[0]: r[1] for r in _table_rows(data / "letters.txt")} + # a value is phones, or CMUdict notation (converted by the template, like the output of the unknown-word model) + exceptions = {r[0].lower(): r[1] for r in _table_rows(data / "exceptions.txt") if " " not in r[0]} + # a name of several words: "w1 w2 ..." -> one pronunciation per word; first word -> the longest name it starts + names: dict[str, Any] = {} + name_starts: dict[str, int] = {} + for r in _table_rows(data / "exceptions.txt"): + words = r[0].lower().split() + if len(words) > 1: + names[" ".join(words)] = [part.strip() for part in r[1].split("|")] + name_starts[words[0]] = max(name_starts.get(words[0], 0), len(words)) + # phoneme (CMUdict, no stress) -> {letters: log probability}: aligns the letters of a word to its phonemes + with open(dir_model / "phonemizer" / "align.json", encoding="utf-8") as f: + align = json.load(f) + # abbreviation -> [when, words] + abbreviations = {r[0]: [r[1], r[2]] for r in _table_rows(data / "abbreviations.txt")} + # chat spelling -> [words to say ("*LOL": letter by letter, "-": nothing), only as a reply by itself], see chat.txt + chat = {r[0].lower(): [r[1] if len(r) > 1 else "-", len(r) > 2] for r in _table_rows(data / "chat.txt")} + # accented latin letter -> plain letter(s): "café" is in the dictionary as "cafe" (dizione: _plain_letter) + accents = {"ß": "ss", "æ": "ae", "Æ": "Ae", "œ": "oe", "Œ": "Oe", "ø": "o", "Ø": "O", "đ": "d", "ł": "l", "Ł": "L"} + for cp in range(0x80, 0x2000): + char = chr(cp) + if char.isalpha() and char not in accents: + plain = "".join(c for c in unicodedata.normalize("NFKD", char) if not unicodedata.combining(c)) + if plain.isascii() and plain.isalpha(): + accents[char] = plain + # compatibility forms of the text (NFKC), a character at a time: "…" is "...", "fi" is "fi", "№" is "No", full + # width letters. Sequences that NFKC would compose are left as they are + nfkc: dict[str, str] = {} + for cp in list(range(0x80, 0x3000)) + list(range(0xFB00, 0xFB07)) + list(range(0xFF01, 0xFF5F)): + if unicodedata.normalize("NFKC", chr(cp)) != chr(cp): + nfkc[chr(cp)] = unicodedata.normalize("NFKC", chr(cp)) + # units after a number: name -> [one, many]; "exact" ones are written in one letter case only ("m", not "M") + units: dict[str, Any] = {} + exact_units: dict[str, Any] = {} + for r in _table_rows(data / "units.txt"): + if len(r) > 3 and r[3] == "exact": + exact_units[r[0]] = [r[1], r[2]] + else: + units[r[0].lower()] = [r[1], r[2]] + # the unit names as a pattern of tts_norm_scan(), the longest first; a unit does not stop inside a word + unit_names = sorted(set(units) | set(exact_units), key=lambda name: (-len(name), name)) + # (the pattern ignores the case of ASCII letters only, the greek letter is written in both) + unit_pattern = "|".join("".join("[μΜ]" if c == "μ" else c if c.isalnum() else "%" + c for c in name) + "(?![A-Za-z])" for name in unit_names) + # endings of file names and addresses: "word" (dot com) or "letters" (dot P D F) + endings = {r[0]: (r[1] if len(r) > 1 else "") for r in _table_rows(data / "endings.txt")} + out = { + "lexicon": lexicon, + "functions": functions, + "phrases": phrases, + "letters": letters, + "exceptions": exceptions, + "abbreviations": abbreviations, + "align": align, + "names": names, + "chat": chat, + "accents": accents, + "nfkc": nfkc, + "units": units, + "exact_units": exact_units, + "endings": endings, + "patterns": {"units": unit_pattern}, + "name_starts": name_starts, + } + out.update(_homograph_dicts(dir_model, data)) + return out + + +def _homograph_dicts(dir_model: Path, data: Path) -> dict[str, dict[str, Any]]: + # words spelled alike and pronounced differently (dizione homographs.py): a linear classifier on the neighbouring + # words, and hand-written rules that are tried first. Weights are stored x10000 (they have four decimals), so the + # template adds integers. + path = dir_model / "phonemizer" / "homographs.json" + if not path.is_file(): + return {"homographs": {}, "homograph_shared": {}, "homograph_plurals": {}, "homograph_rules": {}} + with open(path, encoding="utf-8") as f: + source = json.load(f) + + def fixed(x: float) -> int: + value = round(x * 10000) + if abs(value - x * 10000) > 1e-6: + raise ValueError(f"homographs.json: weight {x} has more than four decimals") + return value + + words: dict[str, Any] = {} + for word, entry in source["words"].items(): + model = entry["model"] + noun_verb = model["kind"] == "noun-verb" + if not noun_verb and model["kind"] != "senses": + raise ValueError(f"homographs.json: unknown model kind {model['kind']!r}") + words[word] = { + # sense: [id, role, phones] + "senses": [[s["id"], s["role"], s["phones"]] for s in entry["senses"]], + # noun-verb: one score for the verb reading; else one score per sense + "noun_verb": noun_verb, + "bias": [fixed(model["bias"])] if noun_verb else [fixed(b) for b in model["bias"]], + "weights": [{k: fixed(v) for k, v in w.items()} for w in ([model["weights"]] if noun_verb else model["weights"])], + } + # the weights all noun-or-verb homographs share; "" is the bias + shared = {k: fixed(v) for k, v in source["pooled"]["weights"].items()} + shared[""] = fixed(source["pooled"]["bias"]) + # word -> [[sense id, [[condition, [words]], ...]], ...], see homograph_rules.txt + rules: dict[str, Any] = {} + for r in _table_rows(data / "homograph_rules.txt"): + conditions = [] + for part in r[2].split(";"): + name, _, listed = part.strip().partition(":") + conditions.append([name, listed.split()]) + rules.setdefault(r[0], []).append([r[1], conditions]) + return { + "homographs": words, + "homograph_shared": shared, + "homograph_plurals": {base: 1 for base in source.get("plural_bases", ())}, + "homograph_rules": rules, + } + + +def _load_state(dir_model: Path) -> dict[str, Tensor]: + ckpt = torch.load(dir_model / CHECKPOINT, map_location="cpu", weights_only=True) + if ckpt.get("format_version") != 4: + raise ValueError(f"unsupported tiny-voca checkpoint format {ckpt.get('format_version')}") + return ckpt["model"] + + +def _block_name(name: str) -> tuple[int, str] | None: + # "blocks..." -> (i, "blk...") + parts = name.split(".") + if len(parts) < 4 or parts[0] != "blocks": + return None + bid = int(parts[1]) + module, suffix = ".".join(parts[2:-1]), parts[-1] + return bid, f"blk.{bid}.{BLOCK_MAP[module]}.{suffix}" + + +def _block_tensors(new_name: str, t: Tensor) -> Iterable[tuple[str, Tensor]]: + # depthwise conv [C, 1, K] -> [C, K], the layout of ggml_ssm_conv + if ".ssm_conv1d.weight" in new_name: + yield (new_name, t.squeeze(1)) + return + # separate q, k, v: a model that libllama builds from metadata (the mmproj stacks) has no fused qkv + if ".attn_qkv." in new_name: + for part, chunk in zip(("attn_q", "attn_k", "attn_v"), t.chunk(3, dim=0)): + yield (new_name.replace("attn_qkv", part), chunk.contiguous()) + return + yield (new_name, t) + + +@ModelBase.register("TinyVocaModel") +@ModelBase.example("n4ze3m/tiny-voca") +class TinyVocaTextModel(TextModel): + model_arch = gguf.MODEL_ARCH.TINY_VOCA + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + del remote_hf_model_id + state = _load_state(self.dir_model) + out: dict[str, Callable[[], Tensor]] = {} + for name, t in state.items(): + if name == "tokens.weight" or name.startswith("encoder."): + out[name] = (lambda t=t: t) + return out + + def set_vocab(self): + config = self.hparams["tiny_voca"] + n_vocab = config["model"]["vocab_size"] + tokens: list[str] = [""] * n_vocab + toktypes = [gguf.TokenType.NORMAL] * n_vocab + for text, i in config["vocab"].items(): + tokens[i] = text + if text.startswith("<") and text.endswith(">"): + toktypes[i] = gguf.TokenType.CONTROL + assert all(tokens) + + # the prompt is split into phonemes by the audio pipeline, see mtmd-helper-gen.cpp + 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([0.0] * n_vocab) + self.gguf_writer.add_token_types(toktypes) + self.gguf_writer.add_bos_token_id(config["vocab"][""]) + self.gguf_writer.add_eos_token_id(config["vocab"][""]) + self.gguf_writer.add_pad_token_id(config["vocab"][""]) + self.gguf_writer.add_unk_token_id(config["vocab"][""]) + self.gguf_writer.add_add_bos_token(False) + self.gguf_writer.add_add_eos_token(False) + + dicts = _g2p_dicts(self.dir_model) + if dicts is not None: + template_path = Path(__file__).parent.parent / "models" / "templates" / "n4ze3m-tiny-voca-tts.jinja" + with open(template_path, encoding="utf-8") as f: + self.gguf_writer.add_chat_template([{"name": "tts", "template": f.read()}]) + self.gguf_writer.add_tts_dicts(dicts) + + def set_gguf_parameters(self): + super().set_gguf_parameters() + self.gguf_writer.add_causal_attention(False) + self.gguf_writer.add_pooling_type(gguf.PoolingType.NONE) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + del bid + if name == "tokens.weight": + yield ("token_embd.weight", data_torch) + return + if name.startswith("encoder.norm."): + yield ("output_norm." + name.rsplit(".", 1)[1], data_torch) + return + res = _block_name(name.removeprefix("encoder.")) + if res is None: + raise ValueError(f"unexpected tensor {name}") + yield from _block_tensors(res[1], data_torch) + + def tensor_force_quant(self, name, new_name, bid, n_dims): + del name, bid, n_dims + # ggml_ssm_conv takes F32 weights; token_embd is also read row by row on the host side + if ".ssm_conv1d." in new_name or new_name == "token_embd.weight": + return gguf.GGMLQuantizationType.F32 + return False + + +@ModelBase.register("TinyVocaModel") +@ModelBase.example("n4ze3m/tiny-voca") +class TinyVocaMmprojModel(MmprojModel): + has_vision_encoder = False + has_audio_encoder = False + + def get_audio_config(self) -> dict[str, Any] | None: + return self.global_config.get("audio_config") + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + del remote_hf_model_id + state = _load_state(self.dir_model) + out: dict[str, Callable[[], Tensor]] = {} + for name, t in state.items(): + if name.startswith("encoder.") or name in ("voices.weight", "frame_voices.weight"): + continue + out[name] = (lambda t=t: t) + return out + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + return item + + def set_gguf_parameters(self): + c = self.global_config["tiny_voca"]["model"] + self.gguf_writer.add_file_type(self.ftype) + self.gguf_writer.add_clip_has_gen_audio_encoder(True) + self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.TINY_VOCA) + self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_gen_audio_embedding_length(c["channels"]) + self.gguf_writer.add_gen_audio_feed_forward_length(c["feedforward"]) + self.gguf_writer.add_gen_audio_block_count(c["acoustic_layers"]) + self.gguf_writer.add_gen_audio_head_count(c["heads"]) + self.gguf_writer.add_gen_audio_attention_layernorm_eps(1e-5) + self.gguf_writer.add_gen_audio_default_voice(DEFAULT_VOICE) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + del bid + # from generate_extra_tensors(), named already + if name.startswith(("voice.", "a.gen.")): + yield (name, data_torch) + return + stack, _, rest = name.partition(".") + if stack in STACK_PREFIX: + prefix = STACK_PREFIX[stack] + if rest.startswith("norm."): + yield (prefix + "output_norm." + rest.rsplit(".", 1)[1], data_torch) + return + res = _block_name(rest) + if res is None: + raise ValueError(f"unexpected tensor {name}") + yield from _block_tensors(prefix + res[1], data_torch) + return + module, suffix = name.rsplit(".", 1) + if module not in MMPROJ_MAP: + raise ValueError(f"unexpected tensor {name}") + yield (MMPROJ_MAP[module] + "." + suffix, data_torch) + + def tensor_force_quant(self, name, new_name, bid, n_dims): + del name, bid + # the blocks of the stacks are loaded by libllama, like the text model + if new_name.startswith(tuple(STACK_PREFIX.values())) and ".ssm_conv1d." not in new_name and n_dims >= 2: + return False + # the rest is small and partly read on the host + return gguf.GGMLQuantizationType.F32 + + def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: + # the unknown-word model of dizione (letters -> CMUdict phonemes), run on the host by mtmd_gen_audio_g2p() + g2p_dir = self.dir_model / "phonemizer" + if (g2p_dir / "g2p.npz").is_file(): + with open(g2p_dir / "g2p.json", encoding="utf-8") as f: + settings = json.load(f) + if settings["letters"] != G2P_LETTERS or settings["symbols"] != G2P_SYMBOLS or settings["convs"] != 0 or settings["slots"] != 2: + raise ValueError("unsupported g2p model in phonemizer/g2p.json") + with np.load(g2p_dir / "g2p.npz") as arrays: + for name in arrays.files: + yield ("a.gen.g2p." + name.replace("__", "."), torch.from_numpy(arrays[name].astype(np.float32))) + config = self.global_config["tiny_voca"] + state = _load_state(self.dir_model) + # a voice row is the embedding added to the encoder input, then the one added to the frames + for i, voice in enumerate(config["voices"]): + yield (f"voice.{voice}", torch.cat([state["voices.weight"][i], state["frame_voices.weight"][i]]).float()) + # class of each token: 0 = pause (special or punctuation), 1 = consonant or , 2 = vowel + vocab = config["vocab"] + cls = torch.zeros(len(vocab), dtype=torch.float32) + for p in CONSONANTS + ("",): + cls[vocab[p]] = 1.0 + for p in VOWELS: + cls[vocab[p]] = 2.0 + yield ("a.gen.token_class", cls) diff --git a/conversion/vibevoice_asr.py b/conversion/vibevoice_asr.py new file mode 100644 index 000000000000..f160c0e01985 --- /dev/null +++ b/conversion/vibevoice_asr.py @@ -0,0 +1,157 @@ +from __future__ import annotations + +from typing import Any, Callable, Iterable, TYPE_CHECKING + +if TYPE_CHECKING: + from torch import Tensor + +from .base import MmprojModel, ModelBase, gguf +from .qwen import Qwen2Model + + +# the upstream chat_template.jinja is a processor template (list content, audio parts), use plain ChatML with its default system prompt +VIBEVOICE_ASR_CHAT_TEMPLATE = ( + "{%- if messages[0]['role'] == 'system' -%}" + "{{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' -}}" + "{%- set loop_messages = messages[1:] -%}" + "{%- else -%}" + "{{- '<|im_start|>system\\nYou are a helpful assistant that transcribes audio input into text output in JSON format.<|im_end|>\\n' -}}" + "{%- set loop_messages = messages -%}" + "{%- endif -%}" + "{%- for message in loop_messages -%}" + "{{- '<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>\\n' -}}" + "{%- endfor -%}" + "{%- if add_generation_prompt -%}" + "{{- '<|im_start|>assistant\\n' -}}" + "{%- endif -%}" +) + + +@ModelBase.register("VibeVoiceAsrForConditionalGeneration") +@ModelBase.example("microsoft/VibeVoice-ASR-HF") +class VibeVoiceAsrModel(Qwen2Model): + model_arch = gguf.MODEL_ARCH.QWEN2 + + def set_vocab(self): + super().set_vocab() + self.gguf_writer.add_chat_template(VIBEVOICE_ASR_CHAT_TEMPLATE) + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, _ = item + if not name.startswith("language_model."): + return None + return super().filter_tensors(item) + + +@ModelBase.register("VibeVoiceAsrForConditionalGeneration") +class VibeVoiceAsrAudioModel(MmprojModel): + has_vision_encoder = False + has_audio_encoder = True + + # values hard-coded in tools/mtmd/models/vibevoice-asr.cpp + _encoder_consts = {"channels": 1, "kernel_size": 7, "num_filters": 32, "ffn_expansion": 4, "hidden_act": "gelu", "rms_norm_eps": 1e-5} + _encoders = ("acoustic_tokenizer_encoder", "semantic_tokenizer_encoder") + + def get_audio_config(self) -> dict[str, Any] | None: + c = self.global_config["acoustic_tokenizer_encoder_config"] + return { + **c, + "intermediate_size": c["ffn_expansion"] * c["hidden_size"], + "num_attention_heads": 1, + "num_hidden_layers": sum(c["depths"]), + } + + def set_gguf_parameters(self): + super().set_gguf_parameters() + for enc in self._encoders: + c = self.global_config[f"{enc}_config"] + for k, v in self._encoder_consts.items(): + assert c[k] == v, f"{enc}.{k} = {c[k]}, expected {v}" + assert c["depths"] == self.hparams["depths"] and c["downsampling_ratios"] == self.hparams["downsampling_ratios"] + + self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.VIBEVOICE_ASR) + # the input is the raw waveform, one channel takes the place of the mel bins + self.gguf_writer.add_audio_num_mel_bins(1) + self.gguf_writer.add_audio_attention_layernorm_eps(self.hparams["rms_norm_eps"]) + self.gguf_writer.add_audio_conv_kernel_size(self.hparams["kernel_size"]) + # stride of each stage, the stem has none + self.gguf_writer.add_audio_patch_sizes([1] + [int(r) for r in self.hparams["downsampling_ratios"]]) + self.gguf_writer.add_audio_depths([int(d) for d in self.hparams["depths"]]) + + def tensor_force_quant(self, name, new_name, bid, n_dims): + if ".dw." in new_name: + return gguf.GGMLQuantizationType.F32 # ggml_ssm_conv + if ".conv." in new_name and new_name.endswith(".weight"): + 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 + if not name.startswith(cls._encoders + ("multi_modal_projector.",)): + return None + return super().filter_tensors(item) + + _block_tensors = { + "norm.weight": gguf.MODEL_TENSOR.A_ENC_CNX_NORM, + "mixer.conv.weight": gguf.MODEL_TENSOR.A_ENC_CNX_DW, + "mixer.conv.bias": gguf.MODEL_TENSOR.A_ENC_CNX_DW, + "gamma": gguf.MODEL_TENSOR.A_ENC_CNX_LS1, + "ffn_norm.weight": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_NORM, + "ffn.linear1.weight": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_UP, + "ffn.linear1.bias": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_UP, + "ffn.linear2.weight": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_DOWN, + "ffn.linear2.bias": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_DOWN, + "ffn_gamma": gguf.MODEL_TENSOR.A_ENC_CNX_LS2, + } + + # mm.a.mlp.{0,1} + mm.a.mlp_norm.0 for the acoustic connector, {2,3} + 2 for the semantic one + _proj_tensors = { + "acoustic_linear_1": (gguf.MODEL_TENSOR.A_MMPROJ, 0), + "acoustic_norm": (gguf.MODEL_TENSOR.A_MMPROJ_NORM, 0), + "acoustic_linear_2": (gguf.MODEL_TENSOR.A_MMPROJ, 1), + "semantic_linear_1": (gguf.MODEL_TENSOR.A_MMPROJ, 2), + "semantic_norm": (gguf.MODEL_TENSOR.A_MMPROJ_NORM, 2), + "semantic_linear_2": (gguf.MODEL_TENSOR.A_MMPROJ, 3), + } + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + # the layer scales (gamma) have no suffix upstream + suffix = "." + name.rsplit(".", 1)[-1] if name.endswith((".weight", ".bias")) else ".weight" + + if name.startswith("multi_modal_projector."): + key, idx = self._proj_tensors[name.split(".")[1]] + yield (self.format_tensor_name(key, idx, suffix=suffix), data_torch) + return + + enc, _, rest = name.partition(".") + enc_id = self._encoders.index(enc) + parts = rest.split(".") + depths = [int(d) for d in self.hparams["depths"]] + + # causal convs of the stages: 0 = stem, 1..6 = downsample, 7 = head + if rest.startswith("stem.conv."): + conv_id = 0 + elif parts[0] == "conv_layers" and parts[2] == "conv": + conv_id = int(parts[1]) + 1 + elif parts[0] == "head": + conv_id = len(depths) + else: + conv_id = None + if conv_id is not None: + yield (gguf.TENSOR_NAMES[gguf.MODEL_TENSOR.A_ENC_CNX_CONV].format(bid=enc_id, xid=conv_id) + suffix, data_torch) + return + + # ConvNeXt blocks are numbered per stage upstream and flat here + if parts[0] == "stem": + stage, blk, tail = 0, int(parts[2]), ".".join(parts[3:]) + else: + assert parts[0] == "conv_layers" and parts[2] == "stage", name + stage, blk, tail = int(parts[1]) + 1, int(parts[3]), ".".join(parts[4:]) + xid = sum(depths[:stage]) + blk + + key = self._block_tensors[tail] + if key == gguf.MODEL_TENSOR.A_ENC_CNX_DW and tail.endswith(".weight"): + data_torch = data_torch.squeeze(1) # [C, 1, K] -> [C, K] for ggml_ssm_conv + yield (gguf.TENSOR_NAMES[key].format(bid=enc_id, xid=xid) + suffix, data_torch) diff --git a/conversion/voxcpm.py b/conversion/voxcpm.py new file mode 100644 index 000000000000..8fc855830c40 --- /dev/null +++ b/conversion/voxcpm.py @@ -0,0 +1,314 @@ +from __future__ import annotations + +import json +import math +import re +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, TextModel, LazyTorchTensor, gguf, logger +from .drama3 import fold_snake +from .minicpm import MiniCPMModel + +# sample rate of the AudioVAE decoder output, picks the row of the sample-rate conditioning +VAE_OUT_SAMPLE_RATE = 48000 + + +def _load_config(dir_model: Path) -> dict[str, Any] | None: + path = dir_model / "config.json" + if not path.is_file(): + return None + with open(path, encoding="utf-8") as f: + config = json.load(f) + return config if config.get("architecture") == "voxcpm2" else None + + +def _is_voxcpm2_checkpoint(dir_model: Path) -> bool: + return _load_config(dir_model) is not None + + +@ModelBase.register_hparams_loader(_is_voxcpm2_checkpoint) +def _load_voxcpm2_hparams(dir_model: Path) -> dict[str, Any]: + logger.info("gguf: detected VoxCPM2 checkpoint") + config = _load_config(dir_model) + assert config is not None + if config["lm_config"].get("use_mup"): + raise NotImplementedError("VoxCPM2: use_mup = true is not supported") + if config["dit_config"].get("mean_mode"): + raise NotImplementedError("VoxCPM2: dit mean_mode = true is not supported") + if not config.get("residual_lm_no_rope"): + raise NotImplementedError("VoxCPM2: residual LM with RoPE is not supported") + for key in ("hidden_dim", "ffn_dim", "num_heads", "num_layers", "kv_channels"): + if config["encoder_config"][key] != config["dit_config"][key]: + raise NotImplementedError(f"VoxCPM2: LocEnc and LocDiT differ in {key}") + return {**config, "architectures": ["VoxCPM2Model"], "text_config": config["lm_config"], "audio_config": config["dit_config"]} + + +@ModelBase.register("VoxCPM2Model") +@ModelBase.example("openbmb/VoxCPM2") +class VoxCPM2TextModel(MiniCPMModel): + model_arch = gguf.MODEL_ARCH.MINICPM + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, gen = item + # the text-semantic LM is a plain MiniCPM, the rest goes to the mmproj + if not name.startswith("base_lm."): + return None + return super().filter_tensors(("model." + name.removeprefix("base_lm."), gen)) + + def set_gguf_parameters(self): + TextModel.set_gguf_parameters(self) + # use_mup = false: no embedding, residual or logit scaling + self.gguf_writer.add_embedding_scale(1.0) + self.gguf_writer.add_residual_scale(1.0) + self.gguf_writer.add_logit_scale(1.0) + + def set_vocab(self): + # the checkpoint has no tokenizer.model and its tokenizer class is remote code, so read tokenizer.json + # SPM-style BPE: a merged token scores minus its merge rank, so the SPM tokenizer merges in the BPE order + with open(self.dir_model / "tokenizer.json", encoding="utf-8") as f: + tok = json.load(f) + with open(self.dir_model / "tokenizer_config.json", encoding="utf-8") as f: + tok_cfg = json.load(f) + model = tok["model"] + if model["type"] != "BPE" or not model.get("byte_fallback"): + raise NotImplementedError("VoxCPM2: unexpected tokenizer type") + + vocab: dict[str, int] = model["vocab"] + vocab_size = self.hparams["vocab_size"] + tokens = [f"[PAD{i}]" for i in range(vocab_size)] + scores = [-1e9] * vocab_size + toktypes = [gguf.TokenType.UNUSED] * vocab_size + for text, i in vocab.items(): + tokens[i] = text + toktypes[i] = gguf.TokenType.BYTE if re.fullmatch(r"<0x[0-9A-Fa-f]{2}>", text) else gguf.TokenType.NORMAL + for rank, merge in enumerate(model["merges"]): + a, b = merge.split(" ") if isinstance(merge, str) else merge + i = vocab[a + b] + scores[i] = max(scores[i], -float(rank)) + + # the special tokens (e.g. <|audio_start|>) are only listed in tokenizer_config.json + specials = {int(i): t["content"] for i, t in tok_cfg.get("added_tokens_decoder", {}).items() if t.get("special")} + specials.update({t["id"]: t["content"] for t in tok["added_tokens"] if t.get("special")}) + for i, text in specials.items(): + tokens[i] = text + toktypes[i] = gguf.TokenType.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) + special_vocab = gguf.SpecialVocab(self.dir_model, n_vocab=len(tokens)) + special_vocab.add_to_gguf(self.gguf_writer) + + +@ModelBase.register("VoxCPM2Model") +@ModelBase.example("openbmb/VoxCPM2") +class VoxCPM2MmprojModel(MmprojModel): + has_vision_encoder = False + has_audio_encoder = True # AudioVAE encoder, for voice cloning + + _LAYER_MAP = { + "input_layernorm.weight": "ln1", + "self_attn.q_proj.weight": "attn_q", + "self_attn.k_proj.weight": "attn_k", + "self_attn.v_proj.weight": "attn_v", + "self_attn.o_proj.weight": "attn_out", + "post_attention_layernorm.weight": "ln2", + "mlp.gate_proj.weight": "ffn_gate", + "mlp.up_proj.weight": "ffn_up", + "mlp.down_proj.weight": "ffn_down", + } + + # libllama names, mtmd loads the residual LM as a text model + _RES_LAYER_MAP = { + "input_layernorm.weight": "attn_norm", + "self_attn.q_proj.weight": "attn_q", + "self_attn.k_proj.weight": "attn_k", + "self_attn.v_proj.weight": "attn_v", + "self_attn.o_proj.weight": "attn_output", + "post_attention_layernorm.weight": "ffn_norm", + "mlp.gate_proj.weight": "ffn_gate", + "mlp.up_proj.weight": "ffn_up", + "mlp.down_proj.weight": "ffn_down", + } + + _PROJ_MAP = { + "fsq_layer.in_proj": "a.gen.fsq.in", + "fsq_layer.out_proj": "a.gen.fsq.out", + "enc_to_lm_proj": "a.gen.enc_to_lm", + "lm_to_dit_proj": "a.gen.lm_to_dit", + "res_to_dit_proj": "a.gen.res_to_dit", + "fusion_concat_proj": "a.gen.fusion", + "stop_proj": "a.gen.stop_proj", + "stop_head": "a.gen.stop_head", + "feat_encoder.in_proj": "a.gen.enc.in_proj", + "feat_decoder.estimator.in_proj": "a.gen.dit.in_proj", + "feat_decoder.estimator.cond_proj": "a.gen.dit.cond_proj", + "feat_decoder.estimator.out_proj": "a.gen.dit.out_proj", + "feat_decoder.estimator.time_mlp.linear_1": "a.gen.dit.time_mlp.0", + "feat_decoder.estimator.time_mlp.linear_2": "a.gen.dit.time_mlp.1", + } + + def set_gguf_parameters(self): + lm = self.global_config["lm_config"] + dit = self.global_config["dit_config"] + vae = self.global_config["audio_vae_config"] + self.gguf_writer.add_file_type(self.ftype) + + # LocEnc + LocDiT + residual LM + AudioVAE decoder, LocEnc has the hparams of LocDiT + self.gguf_writer.add_clip_has_gen_audio_encoder(True) + self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.VOXCPM2_GEN) + self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_gen_audio_embedding_length(dit["hidden_dim"]) + self.gguf_writer.add_gen_audio_feed_forward_length(dit["ffn_dim"]) + self.gguf_writer.add_gen_audio_block_count(dit["num_layers"]) + self.gguf_writer.add_gen_audio_head_count(dit["num_heads"]) + self.gguf_writer.add_gen_audio_head_count_kv(lm["num_key_value_heads"]) + self.gguf_writer.add_gen_audio_attention_layernorm_eps(lm["rms_norm_eps"]) + + # AudioVAE encoder: raw waveform -> latents, LocEnc in the gen model then makes the backbone rows + self.gguf_writer.add_clip_has_audio_encoder(True) + self.gguf_writer.add_clip_audio_projector_type(gguf.VisionProjectorType.VOXCPM2_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(0) + self.gguf_writer.add_audio_embedding_length(vae["encoder_dim"]) + self.gguf_writer.add_audio_feed_forward_length(vae["encoder_dim"]) + self.gguf_writer.add_audio_head_count(1) + self.gguf_writer.add_audio_attention_layernorm_eps(lm["rms_norm_eps"]) + # the ODE solver, the RoPE factors and the VAE layout are hard-coded in tools/mtmd + + def tensor_force_quant(self, name, new_name, bid, n_dims): + # the AudioVAE convs and the 1D tensors stay F32 + if new_name.startswith(("a.vae.", "a.gen.vae.")) or n_dims < 2: + return gguf.GGMLQuantizationType.F32 + 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: + if item[0].startswith("base_lm."): + return None + return item + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + # already named by generate_extra_tensors() + if name.startswith("a."): + yield (name, data_torch) + return + + # dt is always 0 (mean_mode = false), delta_time_mlp gives a constant that is folded into the time_mlp bias + if name.startswith("feat_decoder.estimator.delta_time_mlp."): + return + if name == "feat_decoder.estimator.time_mlp.linear_2.bias": + data_torch = LazyTorchTensor.to_eager(data_torch).float() + self._dtime_const() + + if name == "feat_encoder.special_token": + yield ("a.gen.enc.special_token", data_torch.reshape(-1)) + return + + for src, dst in (("residual_lm.", "a.gen.res"), ("feat_encoder.encoder.", "a.gen.enc"), + ("feat_decoder.estimator.decoder.", "a.gen.code")): + if not name.startswith(src): + continue + key = name.removeprefix(src) + if key == "norm.weight": + yield (f"{dst}.output_norm.weight" if dst == "a.gen.res" else f"{dst}.post_ln.weight", data_torch) + return + assert bid is not None, name + key = key.removeprefix(f"layers.{bid}.") + layer_map = self._RES_LAYER_MAP if dst == "a.gen.res" else self._LAYER_MAP + yield (f"{dst}.blk.{bid}.{layer_map[key]}.weight", data_torch) + return + + base, _, suffix = name.rpartition(".") + yield (f"{self._PROJ_MAP[base]}.{suffix}", data_torch) + + # delta_time_mlp(SinusoidalPosEmb(0)), see VoxCPMLocDiTV2.forward() + def _dtime_const(self) -> Tensor: + d = {k: LazyTorchTensor.to_eager(self.model_tensors[f"feat_decoder.estimator.delta_time_mlp.{k}"]()).float() + for k in ("linear_1.weight", "linear_1.bias", "linear_2.weight", "linear_2.bias")} + dim = d["linear_1.weight"].shape[1] + emb = torch.cat([torch.zeros(dim // 2), torch.ones(dim // 2)]) # sin(0), cos(0) + h = torch.nn.functional.silu(d["linear_1.weight"] @ emb + d["linear_1.bias"]) + return d["linear_2.weight"] @ h + d["linear_2.bias"] + + @staticmethod + def _wn(sd: dict[str, Tensor], prefix: str) -> Tensor: + # torch weight norm, over every dim but 0 + g, v = sd[prefix + ".weight_g"].float(), sd[prefix + ".weight_v"].float() + return g * v / v.flatten(1).norm(dim=1).view(-1, *[1] * (v.dim() - 1)) + + def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: + # LongRoPE factors of LocEnc and LocDiT, picked as in MiniCPMLongRoPE._set_cos_sin_cache() + lm = self.global_config["lm_config"] + rope = lm["rope_scaling"] + if rope.get("type") != "longrope": + raise NotImplementedError(f"VoxCPM2: unexpected rope_scaling {rope.get('type')}") + if lm["max_position_embeddings"] > rope["original_max_position_embeddings"]: + raise NotImplementedError("VoxCPM2: the long RoPE factors also scale cos/sin, not supported") + yield ("a.gen.rope_factors", torch.tensor(rope["short_factor"], dtype=torch.float32)) + + path = self.dir_model / "audiovae.pth" + logger.info(f"gguf: loading AudioVAE from '{path}'") + sd = torch.load(str(path), map_location="cpu", mmap=True, weights_only=True) + sd = sd.get("state_dict", sd) + vae = self.global_config["audio_vae_config"] + + def conv(dst: str, src: str) -> Iterable[tuple[str, Tensor]]: + yield (f"{dst}.weight", self._wn(sd, src)) + yield (f"{dst}.bias", sd[src + ".bias"].float()) + + def snake(dst: str, src: str) -> Iterable[tuple[str, Tensor]]: + alpha, beta = fold_snake(sd[src + ".alpha"]) + yield (f"{dst}.alpha", alpha) + yield (f"{dst}.beta", beta) + + def res_units(dst: str, src: str, first: int) -> Iterable[tuple[str, Tensor]]: + # dilation 1, 3, 9: Snake, depthwise conv k = 7, Snake, conv k = 1 + for r in range(3): + s = f"{src}.{first + r}.block" + d = f"{dst}.res.{r}" + yield from snake(f"{d}.snake1", f"{s}.0") + yield from conv(f"{d}.conv1", f"{s}.1") + yield from snake(f"{d}.snake2", f"{s}.2") + yield from conv(f"{d}.conv2", f"{s}.3") + + # encoder: conv, then per stride (3 residual units, Snake, strided conv), then fc_mu + p = "a.vae.enc" + yield from conv(f"{p}.conv_in", "encoder.block.0") + for b in range(len(vae["encoder_rates"])): + s = f"encoder.block.{b + 1}.block" + yield from res_units(f"{p}.blk.{b}", s, 0) + yield from snake(f"{p}.blk.{b}.snake", f"{s}.3") + yield from conv(f"{p}.blk.{b}.down", f"{s}.4") + yield from conv(f"{p}.fc_mu", "encoder.fc_mu") + + # decoder: depthwise conv, conv k = 1, then per stride (sample-rate scale and bias, Snake, transposed conv, 3 residual units), then Snake, conv + bounds = vae["sr_bin_boundaries"] + sr_idx = sum(1 for b in bounds if b < VAE_OUT_SAMPLE_RATE) # torch.bucketize + if vae["out_sample_rate"] != VAE_OUT_SAMPLE_RATE: + raise NotImplementedError(f"VoxCPM2: unexpected out_sample_rate {vae['out_sample_rate']}") + p = "a.gen.vae" + yield from conv(f"{p}.conv_in_dw", "decoder.model.0") + yield from conv(f"{p}.conv_in", "decoder.model.1") + n_up = len(vae["decoder_rates"]) + for b in range(n_up): + c = f"decoder.sr_cond_model.{b + 2}" + yield (f"{p}.blk.{b}.sr_scale", sd[c + ".scale_embed.weight"][sr_idx].float()) + yield (f"{p}.blk.{b}.sr_bias", sd[c + ".bias_embed.weight"][sr_idx].float()) + s = f"decoder.model.{b + 2}.block" + yield from snake(f"{p}.blk.{b}.snake", f"{s}.0") + yield from conv(f"{p}.blk.{b}.up", f"{s}.1") + yield from res_units(f"{p}.blk.{b}", s, 2) + yield from snake(f"{p}.post_snake", f"decoder.model.{n_up + 2}") + yield from conv(f"{p}.conv_out", f"decoder.model.{n_up + 3}") + + assert math.prod(vae["encoder_rates"]) * VAE_OUT_SAMPLE_RATE == math.prod(vae["decoder_rates"]) * vae["sample_rate"] diff --git a/conversion/yue2.py b/conversion/yue2.py new file mode 100644 index 000000000000..2242af8ebf60 --- /dev/null +++ b/conversion/yue2.py @@ -0,0 +1,234 @@ +from __future__ import annotations + +import base64 +from typing import Any, Callable, Iterable, TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from torch import Tensor + +from .base import ModelBase, MmprojModel, gguf, logger +from .qwen import QwenModel, Qwen3Model + +# token ids of the yue2_infer protocol (protocol.py) +EOD = 151643 +ABC_START, ABC_END = 151847, 151848 +MUSIC_START, MUSIC_END = 151851, 151852 +CODEC_OFFSET, CODEC_SIZE = 151853, 32768 +LATENT_START = 184621 + +# the VAE is a separate repo (m-a-p/YuE2-Vae), downloaded into this subdir of the model dir +VAE_DIR = "vae" + +INSTRUCTIONS = { + "off": "Generate music with codec tokens from the given conditions.", + "melody": "Generate a melody-only ABC transcription without chord symbols, then generate music with codec tokens from the given conditions.", + "full": "Generate a chord-annotated ABC transcription, then generate music with codec tokens from the given conditions.", +} + +# the text is "[Tags]\n diff --git a/tools/ui/src/lib/components/ui/context-menu/context-menu-sub-content.svelte b/tools/ui/src/lib/components/ui/context-menu/context-menu-sub-content.svelte deleted file mode 100644 index 693a0a910d14..000000000000 --- a/tools/ui/src/lib/components/ui/context-menu/context-menu-sub-content.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/drawer/drawer-content.svelte b/tools/ui/src/lib/components/ui/drawer/drawer-content.svelte deleted file mode 100644 index b4f85dd52a9b..000000000000 --- a/tools/ui/src/lib/components/ui/drawer/drawer-content.svelte +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - {@render children?.()} - - diff --git a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte b/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte deleted file mode 100644 index 28c99086fdcc..000000000000 --- a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/input/input.svelte b/tools/ui/src/lib/components/ui/input/input.svelte deleted file mode 100644 index c5718e4d0d4d..000000000000 --- a/tools/ui/src/lib/components/ui/input/input.svelte +++ /dev/null @@ -1,52 +0,0 @@ - - -{#if type === 'file'} - -{:else} - -{/if} diff --git a/tools/ui/src/lib/components/ui/switch/switch.svelte b/tools/ui/src/lib/components/ui/switch/switch.svelte deleted file mode 100644 index 0be9e41940fe..000000000000 --- a/tools/ui/src/lib/components/ui/switch/switch.svelte +++ /dev/null @@ -1,29 +0,0 @@ - - - - - diff --git a/tools/ui/src/lib/components/ui/textarea/textarea.svelte b/tools/ui/src/lib/components/ui/textarea/textarea.svelte deleted file mode 100644 index 7b0511dee757..000000000000 --- a/tools/ui/src/lib/components/ui/textarea/textarea.svelte +++ /dev/null @@ -1,22 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/toggle-group/toggle-group-item.svelte b/tools/ui/src/lib/components/ui/toggle-group/toggle-group-item.svelte deleted file mode 100644 index e9474f61dc76..000000000000 --- a/tools/ui/src/lib/components/ui/toggle-group/toggle-group-item.svelte +++ /dev/null @@ -1,35 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/toggle-group/toggle-group.svelte b/tools/ui/src/lib/components/ui/toggle-group/toggle-group.svelte deleted file mode 100644 index b8953761902c..000000000000 --- a/tools/ui/src/lib/components/ui/toggle-group/toggle-group.svelte +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - diff --git a/tools/ui/src/lib/components/ui/toggle/toggle.svelte b/tools/ui/src/lib/components/ui/toggle/toggle.svelte deleted file mode 100644 index 0d74d04d4f72..000000000000 --- a/tools/ui/src/lib/components/ui/toggle/toggle.svelte +++ /dev/null @@ -1,54 +0,0 @@ - - - - - diff --git a/tools/ui/src/lib/components/ui/utils.ts b/tools/ui/src/lib/components/ui/utils.ts deleted file mode 100644 index 97525cc4290f..000000000000 --- a/tools/ui/src/lib/components/ui/utils.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { type ClassValue, clsx } from 'clsx'; -import { twMerge } from 'tailwind-merge'; - -export function cn(...inputs: ClassValue[]) { - return twMerge(clsx(inputs)); -} - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export type WithoutChild = T extends { child?: any } ? Omit : T; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export type WithoutChildren = T extends { children?: any } ? Omit : T; -export type WithoutChildrenOrChild = WithoutChildren>; -export type WithElementRef = T & { ref?: U | null }; diff --git a/tools/ui/src/lib/constants/code-block.constants.ts b/tools/ui/src/lib/constants/code-block.constants.ts deleted file mode 100644 index 05db575f9ea5..000000000000 --- a/tools/ui/src/lib/constants/code-block.constants.ts +++ /dev/null @@ -1,50 +0,0 @@ -// Constants for the markdown code-block renderer: language/fence handling and CSS classes. - -/** Parsing and escaping helpers for the markdown code-block renderer. */ -export const CODE_BLOCK = { - AMPERSAND_REGEX: /&/g, - /** Language fallback used when no language is specified. */ - DEFAULT_LANGUAGE: 'text', - /** Matches opening/closing markdown code fences. */ - FENCE_PATTERN: /^```|\n```/g, - GT_REGEX: />/g, - /** Matches the language specifier at the start of a code fence. */ - LANG_PATTERN: /^(\w*)\n?/, - LT_REGEX: / | null = null; - let needRefreshByStorage = $state(false); - - const { - // offlineReady, // to do - add installation banners for iOS - needRefresh: pwaNeedRefresh, - updateServiceWorker - } = useRegisterSW({ - onRegisteredSW(swUrl: string, r: ServiceWorkerRegistration | undefined) { - if (swCheckInterval) { - clearInterval(swCheckInterval); - } - - swCheckInterval = setInterval(async () => { - if (!r || r.installing || !navigator?.onLine) return; - - try { - const resp = await fetch(swUrl, { - cache: SW_CONFIG.UPDATE_FETCH_OPTIONS.CACHE, - headers: { - cache: SW_CONFIG.UPDATE_FETCH_OPTIONS.HEADERS.CACHE, - 'cache-control': SW_CONFIG.UPDATE_FETCH_OPTIONS.HEADERS.CACHE_CONTROL - } - }); - - if (resp?.status === 200) { - await r.update(); - } - } catch (e) { - console.error(e); - } - }, SW_CONFIG.CHECK_INTERVAL_MS); - }, - onRegisterError(error: unknown) { - console.error('[PWA] SW registration error:', error); - } - }); - - // Detect version mismatch via localStorage. - // _app/version.json is SvelteKit's native version file for PWA cache invalidation. - // This comparison detects server upgrades for non-PWA users. - $effect(() => { - if (!browser) return; - - // PWA pages update via the service worker path; the storage check is the non-PWA fallback only - if (navigator.serviceWorker?.controller) return; - - const currentVersion = versionStore.frontend; - - if (!currentVersion) return; - - try { - const storedVersion = localStorage.getItem(BUILD_VERSION_LOCALSTORAGE_KEY); - - needRefreshByStorage = !!storedVersion && storedVersion !== currentVersion; - localStorage.setItem(BUILD_VERSION_LOCALSTORAGE_KEY, currentVersion); - } catch { - needRefreshByStorage = false; - } - }); - - return { - /** Writable that is true when a PWA service worker update is available */ - get needRefresh() { - return pwaNeedRefresh; - }, - /** Version mismatch detected via localStorage (non-PWA users) */ - get needRefreshByStorage() { - return needRefreshByStorage; - }, - updateServiceWorker - }; -} diff --git a/tools/ui/src/lib/stores/version.svelte.ts b/tools/ui/src/lib/stores/version.svelte.ts deleted file mode 100644 index 5a86a575bfb8..000000000000 --- a/tools/ui/src/lib/stores/version.svelte.ts +++ /dev/null @@ -1,65 +0,0 @@ -/** - * versionStore - Build version information - * - * - `build`: llama.cpp build number from `build.json`, embedded at llama.cpp - * build time (LLAMA_BUILD_NUMBER). Shown in the UI when `showBuildVersion` - * is enabled. - * - `frontend`: frontend build version from SvelteKit's `_app/version.json`, - * generated by the @vite-pwa/sveltekit plugin. Changes on every build, so - * comparing it against localStorage reliably detects server upgrades. - * - * In dev mode both fall back to `'dev'`. - */ - -import { browser } from '$app/environment'; -import { base } from '$app/paths'; - -class VersionStore { - build = $state(''); - frontend = $state(''); - - /** - * Fetch the version files. Called by initStores(); order-independent, - * so it runs in the background. - */ - initialize(): void { - if (!browser) return; - - if (import.meta.env.DEV) { - this.build = 'dev'; - this.frontend = 'dev'; - - return; - } - - void this.load(); - } - - private async load(): Promise { - try { - const res = await fetch(`${base}/build.json`, { cache: 'no-store' }); - - if (res.ok) { - const data = await res.json(); - - this.build = data.version ?? ''; - } - } catch { - // build.json missing or unreachable - leave as empty string - } - - try { - const res = await fetch(`${base}/_app/version.json`, { cache: 'no-store' }); - - if (res.ok) { - const data = await res.json(); - - this.frontend = data.version ?? ''; - } - } catch { - // version.json missing or unreachable - leave as empty string - } - } -} - -export const versionStore = new VersionStore(); diff --git a/tools/ui/src/lib/utils/css.ts b/tools/ui/src/lib/utils/css.ts deleted file mode 100644 index 99351a7f4493..000000000000 --- a/tools/ui/src/lib/utils/css.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Converts a rem CSS value to pixels based on the document root font size. - */ -export function remToPx(rem: string): number { - const val = parseFloat(rem); - const fontSize = parseFloat(getComputedStyle(document.documentElement).fontSize); - - return val * fontSize; -} diff --git a/tools/ui/src/lib/utils/model-compatibility.ts b/tools/ui/src/lib/utils/model-compatibility.ts deleted file mode 100644 index 4f7e32fe6765..000000000000 --- a/tools/ui/src/lib/utils/model-compatibility.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Model memory estimation. - * - * Mirrors the app's compatibility check (Model+Compatibility.swift): the - * runtime budget is RAM x 0.75 minus a fixed overhead, and a file fits when - * its size with headroom stays under that budget. The result is the smallest - * memory tier that can run the model, so the UI presents an honest machine - * requirement instead of a raw file size. Context length and - * device-specific budgets are deliberately ignored - callers present the - * requirement and let the user judge. - */ -import { - MB_PER_GB, - MEM_TIERS, - MIB_BYTES, - QUANT_WEIGHT, - RAM_BUDGET_RATIO, - RAM_OVERHEAD_MB -} from '$lib/constants'; - -/** - * Smallest memory tier (GB) that can run a model of the given file size, - * or null if nothing fits even the largest tier. - */ -export function minMemoryTierGb(sizeBytes: number): number | null { - if (!sizeBytes) return null; - - const weightMb = (sizeBytes / MIB_BYTES) * QUANT_WEIGHT; - - for (const tier of MEM_TIERS) { - const budgetMb = tier * MB_PER_GB * RAM_BUDGET_RATIO - RAM_OVERHEAD_MB; - - if (weightMb <= budgetMb) return tier; - } - - return null; -} diff --git a/tools/ui/src/lib/utils/near-viewport.ts b/tools/ui/src/lib/utils/near-viewport.ts deleted file mode 100644 index 2af6a6bcfb26..000000000000 --- a/tools/ui/src/lib/utils/near-viewport.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type { ActionReturn } from 'svelte/action'; - -/** Margin around the viewport that already counts as "near". */ -const NEAR_VIEWPORT_MARGIN = '200px'; - -/** - * Calls back once the element comes near the viewport, so per-row work that costs - * a request (avatars, Hub details) does not fire on mount. - */ -export function nearViewport(node: HTMLElement, onNear: () => void): ActionReturn { - if (typeof IntersectionObserver === 'undefined') { - onNear(); - - return {}; - } - - const observer = new IntersectionObserver( - (entries) => { - if (entries.some((entry) => entry.isIntersecting)) { - observer.disconnect(); - onNear(); - } - }, - { rootMargin: NEAR_VIEWPORT_MARGIN } - ); - - observer.observe(node); - - return { - destroy() { - observer.disconnect(); - } - }; -} diff --git a/tools/ui/src/routes/settings/+page.ts b/tools/ui/src/routes/settings/+page.ts deleted file mode 100644 index 3be3d5a9567b..000000000000 --- a/tools/ui/src/routes/settings/+page.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { PageLoad } from './$types'; -import { loadAppRoute } from '$lib/stores/init'; - -export const load: PageLoad = ({ fetch }) => loadAppRoute(fetch); diff --git a/tools/ui/src/virtual-nerdamer.d.ts b/tools/ui/src/virtual-nerdamer.d.ts deleted file mode 100644 index 433fb2b3bd20..000000000000 --- a/tools/ui/src/virtual-nerdamer.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -declare module 'virtual:nerdamer' { - const code: string; - export default code; -} diff --git a/tools/ui/svelte.config.js b/tools/ui/svelte.config.js deleted file mode 100644 index 286a459973d9..000000000000 --- a/tools/ui/svelte.config.js +++ /dev/null @@ -1,38 +0,0 @@ -import adapter from '@sveltejs/adapter-static'; -import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; -import { mdsvex } from 'mdsvex'; - -// CMake sets LLAMA_UI_OUT_DIR to the staging dir under the build tree; manual -// `npm run build` runs without the env var default to ./dist. -const outDir = process.env.LLAMA_UI_OUT_DIR ?? './dist'; -/** @type {import('@sveltejs/kit').Config} */ -const config = { - extensions: ['.svelte', '.svx'], - - kit: { - adapter: adapter({ - assets: outDir, - fallback: 'index.html', - pages: outDir, - precompress: false, - strict: true - }), - output: { - bundleStrategy: 'single' - }, - paths: { - relative: true - }, - router: { type: 'hash' } - }, - - // Consult https://svelte.dev/docs/kit/integrations - // for more information about preprocessors - // mdsvex is for content pages we write ourselves (e.g. release notes reachable from the - // chat app): .svx files compiled to components at build time. No page uses it yet. - // It can't render chat input or messages, which are typed at runtime and go through - // the remark/rehype pipeline in MarkdownContent instead. - preprocess: [vitePreprocess(), mdsvex()] -}; - -export default config; diff --git a/tools/ui/tests/client/components/ChatScreenFormTestWrapper.svelte b/tools/ui/tests/client/components/ChatScreenFormTestWrapper.svelte deleted file mode 100644 index 3e780e80e98a..000000000000 --- a/tools/ui/tests/client/components/ChatScreenFormTestWrapper.svelte +++ /dev/null @@ -1,8 +0,0 @@ - - - - - diff --git a/tools/ui/tests/stories/ChatFormSingleRow.stories.svelte b/tools/ui/tests/stories/ChatFormSingleRow.stories.svelte deleted file mode 100644 index d2879c6fc2be..000000000000 --- a/tools/ui/tests/stories/ChatFormSingleRow.stories.svelte +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - -
- {#each RADII as [radius, label] (radius)} -
- {label} - - -
- {/each} -
-
diff --git a/tools/ui/tests/stories/ChatMessage.stories.svelte b/tools/ui/tests/stories/ChatMessage.stories.svelte deleted file mode 100644 index bec9cbcd3e18..000000000000 --- a/tools/ui/tests/stories/ChatMessage.stories.svelte +++ /dev/null @@ -1,416 +0,0 @@ - - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', true); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - const { conversationsStore } = await import('$lib/stores/conversations/index.svelte'); - - settingsStore.updateConfig('showMessageStats', true); - settingsStore.updateConfig('showRawOutputSwitch', false); - // The toggle reads the before size from the branch, so the story needs - // the summarized turn in the active message list. - conversationsStore.activeMessages = [preCompactionAssistant, compactionMessage]; - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - const { chatActivityStore } = await import('$lib/stores/chat/activity.svelte'); - const { chatStore } = await import('$lib/stores/chat/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - - // The summary request reports its prompt progress through the shared - // processing state; seed one so the story shows the prefill detail. - chatActivityStore.markCompacting('conv-1', compactionPendingMessage.id); - chatStore.processing.setActiveConversation('conv-1'); - chatStore.processing.setState('conv-1', { - contextTotal: 32768, - contextUsed: 10000, - hasNextToken: false, - outputTokensMax: -1, - outputTokensUsed: 0, - progressPercent: 42, - promptProgress: { cache: 0, processed: 4200, time_ms: 6000, total: 10000 }, - promptTokens: 0, - speculative: false, - status: 'preparing', - temperature: 0.8, - tokensDecoded: 0, - tokensPerSecond: 0, - tokensRemaining: -1, - topP: 0.95 - }); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - const { chatActivityStore } = await import('$lib/stores/chat/activity.svelte'); - const { chatStore } = await import('$lib/stores/chat/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - - // Prompt processing is over, so only the generated tokens are reported. - chatActivityStore.markCompacting('conv-1', compactionGeneratingMessage.id); - chatStore.processing.setActiveConversation('conv-1'); - chatStore.processing.setState('conv-1', { - contextTotal: 32768, - contextUsed: 45200, - hasNextToken: true, - outputTokensMax: -1, - outputTokensUsed: 128, - promptTokens: 42200, - speculative: false, - status: 'generating', - temperature: 0.8, - tokensDecoded: 128, - tokensPerSecond: 25, - tokensRemaining: -1, - topP: 0.95 - }); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - // Phase 1: Stream reasoning content in chunks - let reasoningText = - 'I need to think about this carefully. Let me break down the problem:\n\n1. The user is asking for help with something complex\n2. I should provide a thorough and helpful response\n3. I need to consider multiple approaches\n4. The best solution would be to explain step by step\n\nThis approach will ensure clarity and understanding.'; - let reasoningChunk = 'I'; - let i = 0; - - while (i < reasoningText.length) { - const chunkSize = Math.floor(Math.random() * 5) + 3; // Random 3-7 characters - const chunk = reasoningText.slice(i, i + chunkSize); - - reasoningChunk += chunk; - - // Update the reactive state directly - streamingMessage.thinking = reasoningChunk; - - i += chunkSize; - await new Promise((resolve) => setTimeout(resolve, 50)); - } - - const regularText = - "Based on my analysis, here's the solution:\n\n**Step 1:** First, we need to understand the requirements clearly.\n\n**Step 2:** Then we can implement the solution systematically.\n\n**Step 3:** Finally, we test and validate the results.\n\nThis approach ensures we cover all aspects of the problem effectively."; - - let contentChunk = ''; - - i = 0; - - while (i < regularText.length) { - const chunkSize = Math.floor(Math.random() * 5) + 3; // Random 3-7 characters - const chunk = regularText.slice(i, i + chunkSize); - - contentChunk += chunk; - - // Update the reactive state directly - streamingMessage.content = contentChunk; - - i += chunkSize; - await new Promise((resolve) => setTimeout(resolve, 50)); - } - - streamingMessage.timestamp = Date.now(); - }} -> -
- -
-
- - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - // Import the chat store to simulate loading state - const { chatStore } = await import('$lib/stores/chat/index.svelte'); - - // Set loading state to true to trigger the processing UI - chatStore.isLoading = true; - - // Simulate the processing state hook behavior - // This will show the "Generating..." text and parameter details - await new Promise((resolve) => setTimeout(resolve, 100)); - }} -/> diff --git a/tools/ui/tests/stories/ChatScreenForm.stories.svelte b/tools/ui/tests/stories/ChatScreenForm.stories.svelte deleted file mode 100644 index ab23974b6b9c..000000000000 --- a/tools/ui/tests/stories/ChatScreenForm.stories.svelte +++ /dev/null @@ -1,95 +0,0 @@ - - - { - const editor = await canvas.findByRole('textbox'); - const submitButton = await canvas.findByRole('button', { name: 'Send' }); - - // Expect the input to be focused after the component is mounted - await expect(editor).toHaveFocus(); - - // Expect the submit button to be disabled - await expect(submitButton).toBeDisabled(); - - const text = 'What is the meaning of life?'; - - await userEvent.clear(editor); - await userEvent.type(editor, text); - - await expect(editor).toHaveTextContent(text); - - const fileInput = document.querySelector('input[type="file"]'); - - await expect(fileInput).not.toHaveAttribute('accept'); - }} -/> - - - - { - const jpgAttachment = canvas.getByAltText('1.jpg'); - const svgAttachment = canvas.getByAltText('hf-logo.svg'); - const pdfFileExtension = canvas.getByText('PDF'); - const pdfAttachment = canvas.getByText('example.pdf'); - const pdfSize = canvas.getByText('342.82 KB'); - - await expect(jpgAttachment).toBeInTheDocument(); - await expect(jpgAttachment).toHaveAttribute('src', jpgAsset); - - await expect(svgAttachment).toBeInTheDocument(); - await expect(svgAttachment).toHaveAttribute('src', svgAsset); - - await expect(pdfFileExtension).toBeInTheDocument(); - await expect(pdfAttachment).toBeInTheDocument(); - await expect(pdfSize).toBeInTheDocument(); - }} -/> diff --git a/tools/ui/tests/stories/Introduction.mdx b/tools/ui/tests/stories/Introduction.mdx deleted file mode 100644 index d4c0c792164c..000000000000 --- a/tools/ui/tests/stories/Introduction.mdx +++ /dev/null @@ -1,44 +0,0 @@ -import { Meta } from '@storybook/addon-docs/blocks'; - - - -# llama.cpp Web UI - -Welcome to the **llama-ui** component library! This Storybook showcases the components used in the modern web interface for the llama-server. - -## 🚀 About This Project - -Llama UI is a modern web interface for the llama-server, built with SvelteKit and ShadCN UI. Features include: - -- **Real-time chat conversations** with AI assistants -- **Multi-conversation management** with persistent storage -- **Advanced parameter tuning** for model behavior -- **File upload support** for multimodal interactions -- **Responsive design** that works on desktop and mobile - -## 🎨 Design System - -The UI is built using: - -- **SvelteKit** - Modern web framework with excellent performance -- **Tailwind CSS** - Utility-first CSS framework for rapid styling -- **ShadCN/UI** - High-quality, accessible component library -- **Lucide Icons** - Beautiful, consistent icon set - -## 🔧 Development - -This Storybook serves as both documentation and a development environment for the UI components. Each story demonstrates: - -- **Component variations** - Different states and configurations -- **Interactive examples** - Live components you can interact with -- **Usage patterns** - How components work together -- **Styling consistency** - Unified design language - -## 🚀 Getting Started - -To explore the components: - -1. **Browse the sidebar** to see all available components -2. **Click on stories** to see different component states -3. **Use the controls panel** to interact with component props -4. **Check the docs tab** for detailed component information diff --git a/tools/ui/tests/stories/MarkdownContent.stories.svelte b/tools/ui/tests/stories/MarkdownContent.stories.svelte deleted file mode 100644 index b3203e335969..000000000000 --- a/tools/ui/tests/stories/MarkdownContent.stories.svelte +++ /dev/null @@ -1,139 +0,0 @@ - - - - - - - - - - - - - - - - - { - const { canvasElement } = context; - - // Wait for component to render - await new Promise((resolve) => setTimeout(resolve, 100)); - - // Find all links in the rendered content - const links = (canvasElement as HTMLElement).querySelectorAll( - 'a[href]' - ) as NodeListOf; - const linkList = Array.from(links) as HTMLAnchorElement[]; - - // Test that we have the expected number of links - expect(links.length).toBeGreaterThan(0); - - // Test each link for proper attributes - links.forEach((link: HTMLAnchorElement) => { - const href = link.getAttribute('href'); - - // Test that external links have proper security attributes - if (href && (href.startsWith('http://') || href.startsWith('https://'))) { - expect(link.getAttribute('target')).toBe('_blank'); - expect(link.getAttribute('rel')).toBe('noopener noreferrer'); - } - }); - - // Test specific links exist - const hugginFaceLink = linkList.find( - (link) => link.getAttribute('href') === 'https://huggingface.co' - ); - - expect(hugginFaceLink).toBeTruthy(); - expect(hugginFaceLink?.textContent).toBe('Hugging Face Homepage'); - - const githubLink = linkList.find( - (link) => link.getAttribute('href') === 'https://github.com/ggml-org/llama.cpp' - ); - - expect(githubLink).toBeTruthy(); - expect(githubLink?.textContent).toBe('GitHub Repository'); - - const openaiLink = linkList.find((link) => link.getAttribute('href') === 'https://openai.com'); - - expect(openaiLink).toBeTruthy(); - expect(openaiLink?.textContent).toBe('OpenAI Website'); - - const googleLink = linkList.find( - (link) => link.getAttribute('href') === 'https://www.google.com' - ); - - expect(googleLink).toBeTruthy(); - expect(googleLink?.textContent).toBe('Google Search'); - - // Test inline links (auto-linked URLs) - const exampleLink = linkList.find( - (link) => link.getAttribute('href') === 'https://example.com' - ); - - expect(exampleLink).toBeTruthy(); - - const pythonDocsLink = linkList.find( - (link) => link.getAttribute('href') === 'https://docs.python.org' - ); - - expect(pythonDocsLink).toBeTruthy(); - - console.log(`✅ URL Links test passed - Found ${links.length} links with proper attributes`); - }} -/> diff --git a/tools/ui/tests/stories/ModelsSelector.stories.svelte b/tools/ui/tests/stories/ModelsSelector.stories.svelte deleted file mode 100644 index 5c59b21a2052..000000000000 --- a/tools/ui/tests/stories/ModelsSelector.stories.svelte +++ /dev/null @@ -1,268 +0,0 @@ - - - - - -
- -
-
- - -
- -
-
- - -
- -
-
- - -
-
- Server model states -
- - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('model-idle', 'Model (idle)', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('model-loading', 'Model (loading)', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('model-loaded', 'Model (loaded)', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('model-sleeping', 'Model (sleeping)', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('model-failed', 'Model (failed)', 'meta')} - /> -
-
- - -
-
- Selection states -
- - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('normal-model', 'Normal Model', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('selected-model', 'Selected Model', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('highlighted-model', 'Highlighted Model', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('fav-model', 'Favorite Model', 'Qwen')} - /> -
-
diff --git a/tools/ui/tests/stories/PwaRefreshAlert.stories.svelte b/tools/ui/tests/stories/PwaRefreshAlert.stories.svelte deleted file mode 100644 index 2a0a0b4bbf6a..000000000000 --- a/tools/ui/tests/stories/PwaRefreshAlert.stories.svelte +++ /dev/null @@ -1,64 +0,0 @@ - - - console.log('reload') }} - name="Default" - play={async ({ canvas }) => { - const title = canvas.getByText('Update available'); - - await expect(title).toBeInTheDocument(); - - const description = canvas.getByText(/A new version is available/); - - await expect(description).toBeInTheDocument(); - - const button = canvas.getByRole('button', { name: 'Reload' }); - - await expect(button).toBeInTheDocument(); - }} -/> - - console.log('reload') }} - name="Hidden" - play={async ({ canvas }) => { - const title = canvas.queryByText('Update available'); - - await expect(title).not.toBeInTheDocument(); - }} -/> - - console.log('reload') - }} - name="ClickReload" - play={async ({ canvas, userEvent }) => { - const button = canvas.getByRole('button', { name: 'Reload' }); - - await expect(button).toBeInTheDocument(); - - await userEvent.click(button); - - const title = canvas.queryByText('Update available'); - - await expect(title).not.toBeInTheDocument(); - - const reloadBtn = canvas.queryByRole('button', { name: 'Reload' }); - - await expect(reloadBtn).not.toBeInTheDocument(); - }} -/> diff --git a/tools/ui/tests/stories/chat/screen/attachments/ChatAttachmentsPreview.stories.svelte b/tools/ui/tests/stories/chat/screen/attachments/ChatAttachmentsPreview.stories.svelte deleted file mode 100644 index f7f828f33f5c..000000000000 --- a/tools/ui/tests/stories/chat/screen/attachments/ChatAttachmentsPreview.stories.svelte +++ /dev/null @@ -1,47 +0,0 @@ - - - - { - await waitFor(() => expect(canvas.getByText('Failed to load PDF images')).toBeInTheDocument(), { - timeout: 5000 - }); - - // a retry loop would flip back to the loading state - await new Promise((resolve) => setTimeout(resolve, 500)); - await expect(canvas.queryByText('Converting PDF to images...')).not.toBeInTheDocument(); - await expect(canvas.getByText('Failed to load PDF images')).toBeInTheDocument(); - }} -> -
- -
-
diff --git a/tools/ui/tests/stories/fixtures/ChatFormSingleRowPreview.svelte b/tools/ui/tests/stories/fixtures/ChatFormSingleRowPreview.svelte deleted file mode 100644 index 6cfc54726fa4..000000000000 --- a/tools/ui/tests/stories/fixtures/ChatFormSingleRowPreview.svelte +++ /dev/null @@ -1,57 +0,0 @@ - - - - -
- -
diff --git a/tools/ui/tests/stories/fixtures/api-docs.ts b/tools/ui/tests/stories/fixtures/api-docs.ts deleted file mode 100644 index 7b499956f8bc..000000000000 --- a/tools/ui/tests/stories/fixtures/api-docs.ts +++ /dev/null @@ -1,160 +0,0 @@ -// API Documentation -export const API_DOCS_MD = String.raw` -# REST API Documentation - -## 🔐 Authentication - -All API requests require authentication using **Bearer tokens**. Include your API key in the Authorization header: - -${'```'}http -GET /api/v1/users -Host: api.example.com -Authorization: Bearer YOUR_API_KEY -Content-Type: application/json -${'```'} - -## 📍 Endpoints - -### Users API - -#### **GET** /api/v1/users - -Retrieve a paginated list of users. - -**Query Parameters:** - -| Parameter | Type | Default | Description | -|-----------|------|---------|-------------| -| page | integer | 1 | Page number | -| limit | integer | 20 | Items per page | -| sort | string | "created_at" | Sort field | -| order | string | "desc" | Sort order | - -**Response:** 200 OK - -${'```'}json -{ - "data": [ - { - "id": "usr_1234567890", - "email": "user@example.com", - "name": "John Doe", - "role": "admin", - "created_at": "2024-01-15T10:30:00Z" - } - ], - "pagination": { - "page": 1, - "limit": 20, - "total": 156, - "pages": 8 - } -} -${'```'} - -#### **POST** /api/v1/users - -Create a new user account. - -**Request Body:** - -${'```'}json -{ - "email": "newuser@example.com", - "password": "SecurePassword123!", - "name": "Jane Smith", - "role": "user" -} -${'```'} - -**Response:** 201 Created - -${'```'}json -{ - "id": "usr_9876543210", - "email": "newuser@example.com", - "name": "Jane Smith", - "role": "user", - "created_at": "2024-01-21T09:15:00Z" -} -${'```'} - -### Error Responses - -The API returns errors in a consistent format: - -${'```'}json -{ - "error": { - "code": "VALIDATION_ERROR", - "message": "Invalid request parameters", - "details": [ - { - "field": "email", - "message": "Email format is invalid" - } - ] - } -} -${'```'} - -### Rate Limiting - -| Tier | Requests/Hour | Burst | -|------|--------------|-------| -| **Free** | 1,000 | 100 | -| **Pro** | 10,000 | 500 | -| **Enterprise** | Unlimited | - | - -**Headers:** -- X-RateLimit-Limit -- X-RateLimit-Remaining -- X-RateLimit-Reset - -### Webhooks - -Configure webhooks to receive real-time events: - -${'```'}javascript -// Webhook payload -{ - "event": "user.created", - "timestamp": "2024-01-21T09:15:00Z", - "data": { - "id": "usr_9876543210", - "email": "newuser@example.com" - }, - "signature": "sha256=abcd1234..." -} -${'```'} - -### SDK Examples - -**JavaScript/TypeScript:** - -${'```'}typescript -import { ApiClient } from '@example/api-sdk'; - -const client = new ApiClient({ - apiKey: process.env.API_KEY -}); - -const users = await client.users.list({ - page: 1, - limit: 20 -}); -${'```'} - -**Python:** - -${'```'}python -from example_api import Client - -client = Client(api_key=os.environ['API_KEY']) -users = client.users.list(page=1, limit=20) -${'```'} - ---- - -📚 [Full API Reference](https://api.example.com/docs) | 💬 [Support](https://support.example.com) -`; diff --git a/tools/ui/tests/stories/fixtures/assets/beautiful-flowers-lotus.webp b/tools/ui/tests/stories/fixtures/assets/beautiful-flowers-lotus.webp deleted file mode 100644 index 6efcffc3b82b..000000000000 Binary files a/tools/ui/tests/stories/fixtures/assets/beautiful-flowers-lotus.webp and /dev/null differ diff --git a/tools/ui/tests/stories/fixtures/blog-post.ts b/tools/ui/tests/stories/fixtures/blog-post.ts deleted file mode 100644 index 3eb2ed7585f8..000000000000 --- a/tools/ui/tests/stories/fixtures/blog-post.ts +++ /dev/null @@ -1,125 +0,0 @@ -// Blog Post Content -export const BLOG_POST_MD = String.raw` -# Understanding Rust's Ownership System - -*Published on March 15, 2024 • 8 min read* - -Rust's ownership system is one of its most distinctive features, enabling memory safety without garbage collection. In this post, we'll explore how ownership works and why it's revolutionary for systems programming. - -## What is Ownership? - -Ownership is a set of rules that governs how Rust manages memory. These rules are checked at compile time, ensuring memory safety without runtime overhead. - -### The Three Rules of Ownership - -1. **Each value has a single owner** -2. **There can only be one owner at a time** -3. **When the owner goes out of scope, the value is dropped** - -## Memory Management Without GC - -Traditional approaches to memory management: - -- **Manual management** (C/C++): Error-prone, leads to bugs -- **Garbage collection** (Java, Python): Runtime overhead -- **Ownership** (Rust): Compile-time safety, zero runtime cost - -## Basic Examples - -### Variable Scope - -${'```'}rust -fn main() { - let s = String::from("hello"); // s comes into scope - - // s is valid here - println!("{}", s); - -} // s goes out of scope and is dropped -${'```'} - -### Move Semantics - -${'```'}rust -fn main() { - let s1 = String::from("hello"); - let s2 = s1; // s1 is moved to s2 - - // println!("{}", s1); // ❌ ERROR: s1 is no longer valid - println!("{}", s2); // ✅ OK: s2 owns the string -} -${'```'} - -## Borrowing and References - -Instead of transferring ownership, you can **borrow** values: - -### Immutable References - -${'```'}rust -fn calculate_length(s: &String) -> usize { - s.len() // s is a reference, doesn't own the String -} - -fn main() { - let s1 = String::from("hello"); - let len = calculate_length(&s1); // Borrow s1 - println!("Length of '{}' is {}", s1, len); // s1 still valid -} -${'```'} - -### Mutable References - -${'```'}rust -fn main() { - let mut s = String::from("hello"); - - let r1 = &mut s; - r1.push_str(", world"); - println!("{}", r1); - - // let r2 = &mut s; // ❌ ERROR: cannot borrow twice -} -${'```'} - -## Common Pitfalls - -### Dangling References - -${'```'}rust -fn dangle() -> &String { // ❌ ERROR: missing lifetime specifier - let s = String::from("hello"); - &s // s will be dropped, leaving a dangling reference -} -${'```'} - -### ✅ Solution - -${'```'}rust -fn no_dangle() -> String { - let s = String::from("hello"); - s // Ownership is moved out -} -${'```'} - -## Benefits - -- ✅ **No null pointer dereferences** -- ✅ **No data races** -- ✅ **No use-after-free** -- ✅ **No memory leaks** - -## Conclusion - -Rust's ownership system eliminates entire classes of bugs at compile time. While it has a learning curve, the benefits in safety and performance are worth it. - -## Further Reading - -- [The Rust Book - Ownership](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html) -- [Rust by Example - Ownership](https://doc.rust-lang.org/rust-by-example/scope/move.html) -- [Rustlings Exercises](https://github.com/rust-lang/rustlings) - ---- - -*Questions? Reach out on [Twitter](https://twitter.com/rustlang) or join the [Rust Discord](https://discord.gg/rust-lang)* -`; diff --git a/tools/ui/tests/stories/fixtures/data-analysis.ts b/tools/ui/tests/stories/fixtures/data-analysis.ts deleted file mode 100644 index 6fec32dad637..000000000000 --- a/tools/ui/tests/stories/fixtures/data-analysis.ts +++ /dev/null @@ -1,124 +0,0 @@ -// Data Analysis Report -export const DATA_ANALYSIS_MD = String.raw` -# Q4 2024 Business Analytics Report - -*Executive Summary • Generated on January 15, 2025* - -## 📊 Key Performance Indicators - -${'```'} -Daily Active Users (DAU): 1.2M (+65% YoY) -Monthly Active Users (MAU): 4.5M (+48% YoY) -User Retention (Day 30): 68% (+12pp YoY) -Average Session Duration: 24min (+35% YoY) -${'```'} - -## 🎯 Product Performance - -### Feature Adoption Rates - -1. **AI Assistant**: 78% of users (↑ from 45%) -2. **Collaboration Tools**: 62% of users (↑ from 38%) -3. **Analytics Dashboard**: 54% of users (↑ from 31%) -4. **Mobile App**: 41% of users (↑ from 22%) - -### Customer Satisfaction - -| Metric | Q4 2024 | Q3 2024 | Change | -|--------|---------|---------|--------| -| **NPS Score** | 72 | 68 | +4 | -| **CSAT** | 4.6/5 | 4.4/5 | +0.2 | -| **Support Tickets** | 2,340 | 2,890 | -19% | -| **Resolution Time** | 4.2h | 5.1h | -18% | - -## 💰 Revenue Metrics - -### Monthly Recurring Revenue (MRR) - -- **Current MRR**: $2.8M (+42% YoY) -- **New MRR**: $340K -- **Expansion MRR**: $180K -- **Churned MRR**: $95K -- **Net New MRR**: $425K - -### Customer Acquisition - -${'```'} -Cost per Acquisition (CAC): $127 (-23% YoY) -Customer Lifetime Value: $1,840 (+31% YoY) -LTV:CAC Ratio: 14.5:1 -Payback Period: 3.2 months -${'```'} - -## 🌍 Geographic Performance - -### Revenue by Region - -1. **North America**: 45% ($1.26M) -2. **Europe**: 32% ($896K) -3. **Asia-Pacific**: 18% ($504K) -4. **Other**: 5% ($140K) - -### Growth Opportunities - -- **APAC**: 89% YoY growth potential -- **Latin America**: Emerging market entry -- **Middle East**: Enterprise expansion - -## 📱 Channel Performance - -### Traffic Sources - -| Channel | Sessions | Conversion | Revenue | -|---------|----------|------------|---------| -| **Organic Search** | 45% | 3.2% | $1.1M | -| **Direct** | 28% | 4.1% | $850K | -| **Social Media** | 15% | 2.8% | $420K | -| **Paid Ads** | 12% | 5.5% | $430K | - -### Marketing ROI - -- **Content Marketing**: 340% ROI -- **Email Campaigns**: 280% ROI -- **Social Media**: 190% ROI -- **Paid Search**: 220% ROI - -## 🔍 User Behavior Analysis - -### Session Patterns - -- **Peak Hours**: 9-11 AM, 2-4 PM EST -- **Mobile Usage**: 67% of sessions -- **Average Pages/Session**: 4.8 -- **Bounce Rate**: 23% (↓ from 31%) - -### Feature Usage Heatmap - -Most used features in order: -1. Dashboard (89% of users) -2. Search (76% of users) -3. Reports (64% of users) -4. Settings (45% of users) -5. Integrations (32% of users) - -## 💡 Recommendations - -1. **Invest** in AI capabilities (+$2M budget) -2. **Expand** sales team in APAC region -3. **Improve** onboarding to reduce churn -4. **Launch** enterprise security features - -## Appendix - -### Methodology - -Data collected from: -- Internal analytics (Amplitude) -- Customer surveys (n=2,450) -- Financial systems (NetSuite) -- Market research (Gartner) - ---- - -*Report prepared by Data Analytics Team • [View Interactive Dashboard](https://analytics.example.com)* -`; diff --git a/tools/ui/tests/stories/fixtures/empty.ts b/tools/ui/tests/stories/fixtures/empty.ts deleted file mode 100644 index 05286e7a783c..000000000000 --- a/tools/ui/tests/stories/fixtures/empty.ts +++ /dev/null @@ -1,2 +0,0 @@ -// Empty state -export const EMPTY_MD = ''; diff --git a/tools/ui/tests/stories/fixtures/math-formulas.ts b/tools/ui/tests/stories/fixtures/math-formulas.ts deleted file mode 100644 index 1355256b20ce..000000000000 --- a/tools/ui/tests/stories/fixtures/math-formulas.ts +++ /dev/null @@ -1,221 +0,0 @@ -/* eslint-disable no-irregular-whitespace */ -// Math Formulas Content -export const MATH_FORMULAS_MD = String.raw` -# Mathematical Formulas and Expressions - -This document demonstrates various mathematical notation and formulas that can be rendered using LaTeX syntax in markdown. - -## Basic Arithmetic - -### Addition and Summation -$$\sum_{i=1}^{n} i = \frac{n(n+1)}{2}$$ - -## Algebra - -### Quadratic Formula -The solutions to $ax^2 + bx + c = 0$ are: -$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$ - -### Binomial Theorem -$$(x + y)^n = \sum_{k=0}^{n} \binom{n}{k} x^{n-k} y^k$$ - -## Calculus - -### Derivatives -The derivative of $f(x) = x^n$ is: -$$f'(x) = nx^{n-1}$$ - -### Integration -$$\int_a^b f(x) \, dx = F(b) - F(a)$$ - -### Fundamental Theorem of Calculus -$$\frac{d}{dx} \int_a^x f(t) \, dt = f(x)$$ - -## Linear Algebra - -### Matrix Multiplication -If $A$ is an $m \times n$ matrix and $B$ is an $n \times p$ matrix, then: -$$C_{ij} = \sum_{k=1}^{n} A_{ik} B_{kj}$$ - -### Eigenvalues and Eigenvectors -For a square matrix $A$, if $Av = \lambda v$ for some non-zero vector $v$, then: -- $\lambda$ is an eigenvalue -- $v$ is an eigenvector - -## Statistics and Probability - -### Normal Distribution -The probability density function is: -$$f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2}$$ - -### Bayes' Theorem -$$P(A|B) = \frac{P(B|A) \cdot P(A)}{P(B)}$$ - -### Central Limit Theorem -For large $n$, the sample mean $\bar{X}$ is approximately: -$$\bar{X} \sim N\left(\mu, \frac{\sigma^2}{n}\right)$$ - -## Trigonometry - -### Pythagorean Identity -$$\sin^2\theta + \cos^2\theta = 1$$ - -### Euler's Formula -$$e^{i\theta} = \cos\theta + i\sin\theta$$ - -### Taylor Series for Sine -$$\sin x = \sum_{n=0}^{\infty} \frac{(-1)^n}{(2n+1)!} x^{2n+1} = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \cdots$$ - -## Complex Analysis - -### Complex Numbers -A complex number can be written as: -$$z = a + bi = r e^{i\theta}$$ - -where $r = |z| = \sqrt{a^2 + b^2}$ and $\theta = \arg(z)$ - -### Cauchy-Riemann Equations -For a function $f(z) = u(x,y) + iv(x,y)$ to be analytic: -$$\frac{\partial u}{\partial x} = \frac{\partial v}{\partial y}, \quad \frac{\partial u}{\partial y} = -\frac{\partial v}{\partial x}$$ - -## Differential Equations - -### First-order Linear ODE -$$\frac{dy}{dx} + P(x)y = Q(x)$$ - -Solution: $y = e^{-\int P(x)dx}\left[\int Q(x)e^{\int P(x)dx}dx + C\right]$ - -### Heat Equation -$$\frac{\partial u}{\partial t} = \alpha \frac{\partial^2 u}{\partial x^2}$$ - -## Number Theory - -### Prime Number Theorem -$$\pi(x) \sim \frac{x}{\ln x}$$ - -where $\pi(x)$ is the number of primes less than or equal to $x$. - -### Fermat's Last Theorem -For $n > 2$, there are no positive integers $a$, $b$, and $c$ such that: -$$a^n + b^n = c^n$$ - -## Set Theory - -### De Morgan's Laws -$$\overline{A \cup B} = \overline{A} \cap \overline{B}$$ -$$\overline{A \cap B} = \overline{A} \cup \overline{B}$$ - -## Advanced Topics - -### Riemann Zeta Function -$$\zeta(s) = \sum_{n=1}^{\infty} \frac{1}{n^s} = \prod_{p \text{ prime}} \frac{1}{1-p^{-s}}$$ - -### Maxwell's Equations -$$\nabla \cdot \mathbf{E} = \frac{\rho}{\epsilon_0}$$ -$$\nabla \cdot \mathbf{B} = 0$$ -$$\nabla \times \mathbf{E} = -\frac{\partial \mathbf{B}}{\partial t}$$ -$$\nabla \times \mathbf{B} = \mu_0\mathbf{J} + \mu_0\epsilon_0\frac{\partial \mathbf{E}}{\partial t}$$ - -### Schrödinger Equation -$$i\hbar\frac{\partial}{\partial t}\Psi(\mathbf{r},t) = \hat{H}\Psi(\mathbf{r},t)$$ - -## Inline Math Examples - -Here are some inline mathematical expressions: - -- The golden ratio: $\phi = \frac{1 + \sqrt{5}}{2} \approx 1.618$ -- Euler's number: $e = \lim_{n \to \infty} \left(1 + \frac{1}{n}\right)^n$ -- Pi: $\pi = 4 \sum_{n=0}^{\infty} \frac{(-1)^n}{2n+1}$ -- Square root of 2: $\sqrt{2} = 1.41421356...$ - -## Fractions and Radicals - -Complex fraction: $\frac{\frac{a}{b} + \frac{c}{d}}{\frac{e}{f} - \frac{g}{h}}$ - -Nested radicals: $\sqrt{2 + \sqrt{3 + \sqrt{4 + \sqrt{5}}}}$ - -## Summations and Products - -### Geometric Series -$$\sum_{n=0}^{\infty} ar^n = \frac{a}{1-r} \quad \text{for } |r| < 1$$ - -### Product Notation -$$n! = \prod_{k=1}^{n} k$$ - -### Double Summation -$$\sum_{i=1}^{m} \sum_{j=1}^{n} a_{ij}$$ - -## Limits - -$$\lim_{x \to 0} \frac{\sin x}{x} = 1$$ - -$$\lim_{n \to \infty} \left(1 + \frac{x}{n}\right)^n = e^x$$ - -## Further Bracket Styles and Amounts - -- \( \mathrm{GL}_2(\mathbb{F}_7) \): Group of invertible matrices with entries in \(\mathbb{F}_7\). -- Some kernel of \(\mathrm{SL}_2(\mathbb{F}_7)\): - \[ - \left\{ \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}, \begin{pmatrix} -1 & 0 \\ 0 & -1 \end{pmatrix} \right\} = \{\pm I\} - \] -- Algebra: -\[ -x = \frac{-b \pm \sqrt{\,b^{2}-4ac\,}}{2a} -\] -- $100 and $12.99 are amounts, not LaTeX. -- I have $10, $3.99 and $x + y$ and $100x$. The amount is $2,000. -- Emma buys 2 cupcakes for $3 each and 1 cookie for $1.50. How much money does she spend in total? -- Maria has $20. She buys a notebook for $4.75 and a pack of pencils for $3.25. How much change does she receive? -- 1 kg の質量は - \[ - E = (1\ \text{kg}) \times (3.0 \times 10^8\ \text{m/s})^2 \approx 9.0 \times 10^{16}\ \text{J} - \] - というエネルギーに相当します。これは約 21 百万トンの TNT が爆発したときのエネルギーに匹敵します。 -- Algebra: \[ -x = \frac{-b \pm \sqrt{\,b^{2}-4ac\,}}{2a} -\] -- Algebraic topology, Homotopy Groups of $\mathbb{S}^3$: -$$\pi_n(\mathbb{S}^3) = \begin{cases} -\mathbb{Z} & n = 3 \\ -0 & n > 3, n \neq 4 \\ -\mathbb{Z}_2 & n = 4 \\ -\end{cases}$$ -- Spacer preceded by backslash: -\[ -\boxed{ -\begin{aligned} -N_{\text{att}}^{\text{(MHA)}} &= -h \bigl[\, d_{\text{model}}\;d_{k} + d_{\text{model}}\;d_{v}\, \bigr] && (\text{Q,K,V の重み})\\ -&\quad+ h(d_{k}+d_{k}+d_{v}) && (\text{バイアス Q,K,V)}\\[4pt] -&\quad+ (h d_{v})\, d_{\text{model}} && (\text{出力射影 }W^{O})\\ -&\quad+ d_{\text{model}} && (\text{バイアス }b^{O}) -\end{aligned}} -\] - -## Formulas in a Table - -| Area | Expression | Comment | -|------|------------|---------| -| **Algebra** | \[ -x = \frac{-b \pm \sqrt{\,b^{2}-4ac\,}}{2a} -\] | Quadratic formula | -| | \[ -(a+b)^{n} = \sum_{k=0}^{n}\binom{n}{k}\,a^{\,n-k}\,b^{\,k} -\] | Binomial theorem | -| | \(\displaystyle \prod_{k=1}^{n}k = n! \) | Factorial definition | -| **Geometry** | \( \mathbf{a}\cdot \mathbf{b} = \|\mathbf{a}\|\,\|\mathbf{b}\|\,\cos\theta \) | Dot product & angle | - -## No math (but chemical) - -Balanced chemical reaction with states: - -\[ -\ce{2H2(g) + O2(g) -> 2H2O(l)} -\] - -The standard enthalpy change for the reaction is: $\Delta H^\circ = \pu{-572 kJ mol^{-1}}$. - ---- - -*This document showcases various mathematical notation and formulas that can be rendered in markdown using LaTeX syntax.* -`; diff --git a/tools/ui/tests/stories/fixtures/mobile-tables.ts b/tools/ui/tests/stories/fixtures/mobile-tables.ts deleted file mode 100644 index 3e9cc3231db3..000000000000 --- a/tools/ui/tests/stories/fixtures/mobile-tables.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Table-heavy answers, to check the table layout at a phone width. -export const JOKES_TABLE_MD = String.raw` -Sure! Here are the jokes in a table: - -| No. | Joke | -|-----|------| -| 1 | Why don't scientists trust atoms? Because they make up everything. | -| 2 | I told my wife she was drawing her eyebrows too high. She looked surprised. | -| 3 | Why did the scarecrow win an award? Because he was outstanding in his field. | -| 4 | I'm reading a book about anti-gravity. It's impossible to put down. | -| 5 | Why don't skeletons fight each other? They don't have the guts. | -| 6 | I used to hate clowns, but they all have their fat-sies. | -| 7 | What do you call a fake noodle? An impasta. | -| 8 | Why did the bicycle fall over? Because it was two-tired. | -| 9 | I would tell you a chemistry joke, but I know I wouldn't get a reaction. | -| 10 | Why did the golfer bring two pairs of pants? In case he got a hole in one. | -`; - -export const WIDE_CELL_TABLE_MD = String.raw` -Some endpoints, in a table, for reference: - -| Name | Endpoint | Description | -|------|----------|-------------| -| Completions | https://huggingface.co/api/models/ggml-org/gpt-oss-20b-GGUF/summary | Long endpoint description | -| Models | ./v1/models | Lists the models loaded in the server slot | -| Props | ./props | Server capabilities and default sampling | -`; diff --git a/tools/ui/tests/stories/fixtures/readme.ts b/tools/ui/tests/stories/fixtures/readme.ts deleted file mode 100644 index e8b573d6c4e3..000000000000 --- a/tools/ui/tests/stories/fixtures/readme.ts +++ /dev/null @@ -1,136 +0,0 @@ -// README Content -export const README_MD = String.raw` -# 🚀 Awesome Web Framework - -[![npm version](https://img.shields.io/npm/v/awesome-framework.svg)](https://www.npmjs.com/package/awesome-framework) -[![Build Status](https://github.com/awesome/framework/workflows/CI/badge.svg)](https://github.com/awesome/framework/actions) -[![Coverage](https://codecov.io/gh/awesome/framework/branch/main/graph/badge.svg)](https://codecov.io/gh/awesome/framework) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) - -> A modern, fast, and flexible web framework for building scalable applications - -## ✨ Features - -- 🎯 **Type-Safe** - Full TypeScript support out of the box -- ⚡ **Lightning Fast** - Built on Vite for instant HMR -- 📦 **Zero Config** - Works out of the box for most use cases -- 🎨 **Flexible** - Unopinionated with sensible defaults -- 🔧 **Extensible** - Plugin system for custom functionality -- 📱 **Responsive** - Mobile-first approach -- 🌍 **i18n Ready** - Built-in internationalization -- 🔒 **Secure** - Security best practices by default - -## 📦 Installation - -${'```'}bash -npm install awesome-framework -# or -yarn add awesome-framework -# or -pnpm add awesome-framework -${'```'} - -## 🚀 Quick Start - -### Create a new project - -${'```'}bash -npx create-awesome-app my-app -cd my-app -npm run dev -${'```'} - -### Basic Example - -${'```'}javascript -import { createApp } from 'awesome-framework'; - -const app = createApp({ - port: 3000, - middleware: ['cors', 'helmet', 'compression'] -}); - -app.get('/', (req, res) => { - res.json({ message: 'Hello World!' }); -}); - -app.listen(() => { - console.log('Server running on http://localhost:3000'); -}); -${'```'} - -## 📖 Documentation - -### Core Concepts - -- [Getting Started](https://docs.awesome.dev/getting-started) -- [Configuration](https://docs.awesome.dev/configuration) -- [Routing](https://docs.awesome.dev/routing) -- [Middleware](https://docs.awesome.dev/middleware) -- [Database](https://docs.awesome.dev/database) -- [Authentication](https://docs.awesome.dev/authentication) - -### Advanced Topics - -- [Performance Optimization](https://docs.awesome.dev/performance) -- [Deployment](https://docs.awesome.dev/deployment) -- [Testing](https://docs.awesome.dev/testing) -- [Security](https://docs.awesome.dev/security) - -## 🛠️ Development - -### Prerequisites - -- Node.js >= 18 -- pnpm >= 8 - -### Setup - -${'```'}bash -git clone https://github.com/awesome/framework.git -cd framework -pnpm install -pnpm dev -${'```'} - -### Testing - -${'```'}bash -pnpm test # Run unit tests -pnpm test:e2e # Run end-to-end tests -pnpm test:watch # Run tests in watch mode -${'```'} - -## 🤝 Contributing - -We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details. - -### Contributors - - - - - -## 📊 Benchmarks - -| Framework | Requests/sec | Latency (ms) | Memory (MB) | -|-----------|-------------|--------------|-------------| -| **Awesome** | **45,230** | **2.1** | **42** | -| Express | 28,450 | 3.5 | 68 | -| Fastify | 41,200 | 2.3 | 48 | -| Koa | 32,100 | 3.1 | 52 | - -*Benchmarks performed on MacBook Pro M2, Node.js 20.x* - -## 📝 License - -MIT © [Awesome Team](https://github.com/awesome) - -## 🙏 Acknowledgments - -Special thanks to all our sponsors and contributors who make this project possible. - ---- - -**[Website](https://awesome.dev)** • **[Documentation](https://docs.awesome.dev)** • **[Discord](https://discord.gg/awesome)** • **[Twitter](https://twitter.com/awesomeframework)** -`; diff --git a/tools/ui/tests/stories/fixtures/storybook-mocks.ts b/tools/ui/tests/stories/fixtures/storybook-mocks.ts deleted file mode 100644 index ac9fb63cd077..000000000000 --- a/tools/ui/tests/stories/fixtures/storybook-mocks.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { modelsStore } from '$lib/stores/models/index.svelte'; -import { serverStore } from '$lib/stores/server.svelte'; - -/** - * Mock server properties for Storybook testing - * This utility allows setting mock server configurations without polluting production code - */ -export function mockServerProps(props: Partial): void { - // Reset any pointer-events from previous tests (dropdown cleanup) - const body = document.querySelector('body'); - - if (body) body.style.pointerEvents = ''; - - // Directly set the props for testing purposes - (serverStore as unknown as { props: ApiLlamaCppServerProps }).props = { - modalities: { - audio: props.modalities?.audio ?? false, - video: props.modalities?.video ?? false, - vision: props.modalities?.vision ?? false - }, - model_path: props.model_path || 'test-model', - ...props - } as ApiLlamaCppServerProps; - - // Set router mode role so activeModelId can be set - (serverStore as unknown as { props: ApiLlamaCppServerProps }).props.role = 'ROUTER'; - - // Also mock modelsStore methods for modality checking - const vision = props.modalities?.vision ?? false; - const audio = props.modalities?.audio ?? false; - const video = props.modalities?.video ?? false; - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (modelsStore as any).modelSupportsVision = () => vision; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (modelsStore as any).modelSupportsAudio = () => audio; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (modelsStore as any).modelSupportsVideo = () => video; - - // Mock models list with a test model so activeModelId can be resolved - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (modelsStore as any).models = [ - { - id: 'test-model', - model: 'test-model', - name: 'Test Model' - } - ]; - - // Mock selectedModelId - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (modelsStore as any).selectedModelId = 'test-model'; -} - -/** - * Reset server store to clean state for testing - */ -export function resetServerStore(): void { - (serverStore as unknown as { props: ApiLlamaCppServerProps }).props = { - modalities: { - audio: false, - video: false, - vision: false - }, - model_path: '' - } as ApiLlamaCppServerProps; - (serverStore as unknown as { error: string }).error = ''; - (serverStore as unknown as { loading: boolean }).loading = false; -} - -/** - * Common mock configurations for Storybook stories - */ -export const mockConfigs = { - audioOnly: { - modalities: { audio: true, vision: false } - }, - bothModalities: { - modalities: { audio: true, vision: true } - }, - noModalities: { - modalities: { audio: false, video: false, vision: false } - }, - visionOnly: { - modalities: { audio: false, vision: true } - } -} as const; diff --git a/tools/ui/tsconfig.json b/tools/ui/tsconfig.json deleted file mode 100644 index 60047e995be7..000000000000 --- a/tools/ui/tsconfig.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "extends": "./.svelte-kit/tsconfig.json", - "compilerOptions": { - "allowJs": true, - "checkJs": true, - "esModuleInterop": true, - "forceConsistentCasingInFileNames": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "sourceMap": true, - "strict": true, - "moduleResolution": "bundler" - }, - "include": [ - ".svelte-kit/ambient.d.ts", - ".svelte-kit/non-ambient.d.ts", - ".svelte-kit/types/**/$types.d.ts", - "vite.config.js", - "vite.config.ts", - "src/**/*.js", - "src/**/*.ts", - "src/**/*.svelte", - "tests/**/*.ts", - "tests/**/*.svelte", - ".storybook/**/*.ts", - ".storybook/**/*.svelte" - ], - "exclude": ["src/lib/services/sandbox-worker.js", "src/lib/vendors/**"] - // Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias - // except $lib which is handled by https://svelte.dev/docs/kit/configuration#files - // - // If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes - // from the referenced tsconfig.json - TypeScript does not merge them in -} diff --git a/ui/README.md b/ui/README.md new file mode 100644 index 000000000000..b70228d0de7c --- /dev/null +++ b/ui/README.md @@ -0,0 +1,37 @@ +# ui + +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 +└── apps/ + └── chat/ Llama Chat, the chat app that llama-server serves +``` + +- [`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. +- [`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`. + +## Releases + +The npm packages are versioned by hand, with semver, and published by CI: + +| Package | Version in | Published by | +| --- | --- | --- | +| `@ggml-org/llama-ui` | `lib/ui/package.json` | [`ui-lib-publish.yml`](../.github/workflows/ui-lib-publish.yml) | +| `@ggml-org/llama-chat` and `llama-chat` | `apps/chat/package.json` and `apps/chat/alias/package.json`, always the same | [`ui-chat-publish.yml`](../.github/workflows/ui-chat-publish.yml) | + +To release, bump the version in the PR that should ship the change: a patch for fixes, a minor for new or changed +features or API while the version is 0.x. When that PR reaches `master` with a version npm does not have yet, the +workflow builds the package and publishes it; any other commit publishes nothing. A version lower than the one on npm +fails the run. + +Llama Chat as bundled in llama-server is not versioned this way: it ships in every llama.cpp release, as `b`. diff --git a/tools/ui/.env.example b/ui/apps/chat/.env.example similarity index 94% rename from tools/ui/.env.example rename to ui/apps/chat/.env.example index a561a68a6560..ed46f9aded97 100644 --- a/tools/ui/.env.example +++ b/ui/apps/chat/.env.example @@ -13,7 +13,7 @@ VITE_PUBLIC_SERVER_ORIGIN='http://localhost:8033' # DEMO_TRACES_DATASET='/' # DEMO_GITHUB_REPO='ggml-org/llama.cpp' # DEMO_SERVER_ORIGIN='http://localhost:9931' -# DEMO_LLAMA_SERVER='../../build/bin/llama-server' +# DEMO_LLAMA_SERVER='../../../build/bin/llama-server' # DEMO_COLOR_SCHEME='light' # Device pixel ratio demos render and record at (1440x900 viewport) # DEMO_SCALE='2' diff --git a/tools/ui/.gitignore b/ui/apps/chat/.gitignore similarity index 100% rename from tools/ui/.gitignore rename to ui/apps/chat/.gitignore diff --git a/tools/ui/.npmrc b/ui/apps/chat/.npmrc similarity index 72% rename from tools/ui/.npmrc rename to ui/apps/chat/.npmrc index 5e0a8e82addf..fd58f2418d44 100644 --- a/tools/ui/.npmrc +++ b/ui/apps/chat/.npmrc @@ -1,8 +1,6 @@ engine-strict=true ignore-scripts=true min-release-age=7 -# Allow root-declared remote tarball dependencies (llama-brand) on npm 12+ -allow-remote=root # The single-bundle production build needs more than the default heap on CI runners; # npm passes this to every script it runs, on every platform node-options=--max-old-space-size=6144 diff --git a/tools/ui/.prettierignore b/ui/apps/chat/.prettierignore similarity index 100% rename from tools/ui/.prettierignore rename to ui/apps/chat/.prettierignore diff --git a/tools/ui/.prettierrc b/ui/apps/chat/.prettierrc similarity index 100% rename from tools/ui/.prettierrc rename to ui/apps/chat/.prettierrc diff --git a/ui/apps/chat/.storybook/color-scheme.ts b/ui/apps/chat/.storybook/color-scheme.ts new file mode 100644 index 000000000000..4ebfb46ee5cf --- /dev/null +++ b/ui/apps/chat/.storybook/color-scheme.ts @@ -0,0 +1,24 @@ +import { MEDIA_QUERIES } from '#lib/constants/pwa.constants.ts'; +import { ColorMode } from '#lib/enums/ui.enums.ts'; +import { modeStorageKey } from 'mode-watcher'; + +/** The class on `` that turns the dark theme on, as mode-watcher sets it. */ +export const DARK_CLASS = ColorMode.DARK; + +/** Turns the dark theme on or off. */ +export function setDarkClass(isDark: boolean) { + document.documentElement.classList.toggle(DARK_CLASS, isDark); +} + +/** + * Sets the dark class from the saved mode-watcher mode, or the system preference + * when there is none. Docs pages render no story, so preview.ts calls this too. + */ +export function applyColorScheme() { + const mode = localStorage.getItem(modeStorageKey.current) || ColorMode.SYSTEM; + const isDark = + mode === ColorMode.DARK || + (mode === ColorMode.SYSTEM && window.matchMedia(MEDIA_QUERIES.PREFERS_DARK).matches); + + setDarkClass(isDark); +} diff --git a/ui/apps/chat/.storybook/decorators/ModeWatcherDecorator.svelte b/ui/apps/chat/.storybook/decorators/ModeWatcherDecorator.svelte new file mode 100644 index 000000000000..82fa0b10ac5c --- /dev/null +++ b/ui/apps/chat/.storybook/decorators/ModeWatcherDecorator.svelte @@ -0,0 +1,27 @@ + + +{#if !forced}{/if} + +{#if children} + {@const Component = children} + + +{/if} diff --git a/ui/apps/chat/.storybook/decorators/TooltipProviderDecorator.svelte b/ui/apps/chat/.storybook/decorators/TooltipProviderDecorator.svelte new file mode 100644 index 000000000000..76d15b48d6af --- /dev/null +++ b/ui/apps/chat/.storybook/decorators/TooltipProviderDecorator.svelte @@ -0,0 +1,13 @@ + + + + {@render children()} + diff --git a/ui/apps/chat/.storybook/main.ts b/ui/apps/chat/.storybook/main.ts new file mode 100644 index 000000000000..3e8c1a39d8dc --- /dev/null +++ b/ui/apps/chat/.storybook/main.ts @@ -0,0 +1,58 @@ +import type { StorybookConfig } from '@storybook/sveltekit'; +import { dirname, resolve } from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +// Llama UI's stories live with the library (ui/lib/ui/tests/stories), which runs and tests them in its own +// Storybook; this one shows them too, under Llama UI, next to Llama Chat's own. The library's front page stays its own. +// Llama Chat's stories take the helpers they share with the library's (the Editorial, the state gallery) from there +// too, as $llama-ui-stories/..., which tsconfig.json maps for TypeScript +const LLAMA_UI_STORIES = resolve(__dirname, '../../../lib/ui/tests/stories'); + +const config: StorybookConfig = { + stories: [ + '../tests/stories/**/*.mdx', + '../tests/stories/**/*.stories.@(js|ts|svelte)', + { + directory: '../../../lib/ui/tests/stories', + files: '{foundations,components,app,models,mockups}/**/*.stories.svelte' + } + ], + addons: [ + '@storybook/addon-svelte-csf', + '@chromatic-com/storybook', + '@storybook/addon-vitest', + '@storybook/addon-a11y', + '@storybook/addon-docs', + '@storybook/addon-mcp' + ], + framework: '@storybook/sveltekit', + viteFinal: async (config) => { + config.server = config.server || {}; + config.server.fs = config.server.fs || {}; + config.server.fs.allow = [ + ...(config.server.fs.allow || []), + resolve(__dirname, '../tests'), + LLAMA_UI_STORIES + ]; + // the library's stories import Storybook from where they live, where only this app's packages are installed + config.resolve = config.resolve || {}; + config.resolve.alias = [ + ...(Array.isArray(config.resolve.alias) + ? config.resolve.alias + : Object.entries(config.resolve.alias || {}).map(([find, replacement]) => ({ + find, + replacement + }))), + { find: '$llama-ui-stories', replacement: LLAMA_UI_STORIES } + ]; + config.resolve.dedupe = [ + ...(config.resolve.dedupe || []), + '@storybook/addon-svelte-csf', + 'storybook' + ]; + return config; + } +}; +export default config; diff --git a/ui/apps/chat/.storybook/manager-head.html b/ui/apps/chat/.storybook/manager-head.html new file mode 100644 index 000000000000..5964c8fa3cb4 --- /dev/null +++ b/ui/apps/chat/.storybook/manager-head.html @@ -0,0 +1,86 @@ + + diff --git a/ui/apps/chat/.storybook/mockups/MacDock.svelte b/ui/apps/chat/.storybook/mockups/MacDock.svelte new file mode 100644 index 000000000000..0c2fdfad9bcf --- /dev/null +++ b/ui/apps/chat/.storybook/mockups/MacDock.svelte @@ -0,0 +1,174 @@ + + + + + +{#snippet tile(app: DockApp)} + + {#if app.name === labelled}{app.name}{/if} + + {#if app.icon} + {app.name} + {:else} + {@const Glyph = app.glyph ?? Folder} + + + + + + + + + + + {/if} + + + +{/snippet} + + + + diff --git a/ui/apps/chat/.storybook/mockups/MacMenuBar.svelte b/ui/apps/chat/.storybook/mockups/MacMenuBar.svelte new file mode 100644 index 000000000000..5a524adb07ce --- /dev/null +++ b/ui/apps/chat/.storybook/mockups/MacMenuBar.svelte @@ -0,0 +1,119 @@ + + + + + + diff --git a/ui/apps/chat/.storybook/mockups/MacStatusIcon.svelte b/ui/apps/chat/.storybook/mockups/MacStatusIcon.svelte new file mode 100644 index 000000000000..2b857aa5ad37 --- /dev/null +++ b/ui/apps/chat/.storybook/mockups/MacStatusIcon.svelte @@ -0,0 +1,56 @@ + + + + + + + + diff --git a/ui/apps/chat/.storybook/mockups/MockDesktop.svelte b/ui/apps/chat/.storybook/mockups/MockDesktop.svelte new file mode 100644 index 000000000000..51facca5111d --- /dev/null +++ b/ui/apps/chat/.storybook/mockups/MockDesktop.svelte @@ -0,0 +1,76 @@ + + + +
+
+ {@render children()} +
+
+ + diff --git a/ui/apps/chat/.storybook/mockups/WindowsTaskbar.svelte b/ui/apps/chat/.storybook/mockups/WindowsTaskbar.svelte new file mode 100644 index 000000000000..dc2e8afdf8bd --- /dev/null +++ b/ui/apps/chat/.storybook/mockups/WindowsTaskbar.svelte @@ -0,0 +1,234 @@ + + + + + + + + diff --git a/ui/apps/chat/.storybook/mockups/index.ts b/ui/apps/chat/.storybook/mockups/index.ts new file mode 100644 index 000000000000..c4783bde1224 --- /dev/null +++ b/ui/apps/chat/.storybook/mockups/index.ts @@ -0,0 +1,15 @@ +// OS mockups for the stories: a desktop's wallpaper, and on it the macOS Dock and menu bar or the Windows taskbar, +// to picture the brand's icons where the apps put them +export { + default as MacDock, + PLACEHOLDERS as MAC_DOCK_PLACEHOLDERS, + type DockApp +} from './MacDock.svelte'; +export { default as MacMenuBar } from './MacMenuBar.svelte'; +export { default as MacStatusIcon } from './MacStatusIcon.svelte'; +export { default as MockDesktop } from './MockDesktop.svelte'; +export { + default as WindowsTaskbar, + PLACEHOLDERS as WINDOWS_TASKBAR_PLACEHOLDERS, + type TaskbarApp +} from './WindowsTaskbar.svelte'; diff --git a/ui/apps/chat/.storybook/preview.ts b/ui/apps/chat/.storybook/preview.ts new file mode 100644 index 000000000000..7e7a58d167a8 --- /dev/null +++ b/ui/apps/chat/.storybook/preview.ts @@ -0,0 +1,142 @@ +import '../src/app.css'; +import { MEDIA_QUERIES } from '#lib/constants/pwa.constants.ts'; +import { SurfaceTheme } from '#lib/enums/ui.enums.ts'; +import { applySurfaceTheme } from '#lib/utils/css.ts'; +// the docs pages' styles, shared with the library's Storybook +import '../../../lib/ui/.storybook/docs.css'; +import { applyColorScheme } from './color-scheme'; +import ModeWatcherDecorator from './decorators/ModeWatcherDecorator.svelte'; +import TooltipProviderDecorator from './decorators/TooltipProviderDecorator.svelte'; +import type { Preview } from '@storybook/sveltekit'; + +applyColorScheme(); +window.matchMedia(MEDIA_QUERIES.PREFERS_DARK).addEventListener('change', applyColorScheme); + +const preview: Preview = { + parameters: { + controls: { + matchers: { + color: /(background|color)$/i, + date: /Date$/i + } + }, + + backgrounds: { + disabled: true + }, + + options: { + // sidebar sections: the introduction and the guidelines for agents, then the two layers as the code has them. + // Llama UI is the library (ui/lib/ui): its foundations, base components, app components, Model UI and mockups. + // Llama Chat is the app (ui/apps/chat): its own foundations, then one folder per src/lib/components/app/, + // the full chat screen leading Chat. The brand and communications are in llama-brand's Storybook + storySort: { + order: [ + 'Introduction', + 'Agents', + ['Design guidelines'], + 'Llama UI', + [ + 'Foundations', + ['Colors', 'Typography', 'Sizing', 'Shapes', 'Elevation', 'Surfaces'], + 'Components', + ['Actions', 'Forms', 'Display', 'Overlays', 'Navigation'], + 'App components', + 'Models', + 'Mockups' + ], + 'Llama Chat', + [ + 'Foundations', + ['Safe areas', 'Brand'], + 'Chat', + [ + 'ChatScreen', + ['ChatScreen', '*'], + 'ChatForm', + 'ChatMessages', + 'ChatAttachments', + 'ChatTabs' + ], + 'Content', + 'Models', + 'MCP', + 'Navigation', + 'Settings', + ['DialogSettingsChat', 'Navigation', 'Sections'], + 'Dialogs', + 'Forms', + 'Actions', + 'Badges', + 'Misc', + 'Servers', + 'PWA' + ] + ] + } + }, + + a11y: { + // 'todo' shows violations in the Accessibility panel and the test UI without failing a test; 'error' would + // fail CI on them. Not yet 'error': about half the stories fail it, most on colour contrast (the muted + // foreground on the light surfaces, below 4.5:1) and nested interactive controls, which need design changes + // rather than story fixes. Switch once those are settled + test: 'todo' + } + }, + // read by tests/stories/pace.ts; the test runner always plays at full speed + globalTypes: { + interactionPace: { + description: 'Speed of the interactions a story plays', + toolbar: { + dynamicTitle: true, + icon: 'timer', + items: [ + { title: 'Human pace', value: 'human' }, + { title: 'Instant', value: 'instant' } + ], + title: 'Interaction pace' + } + }, + // the light surface theme: Paper (white panels on a grey page) or Matte (grey glass on white) + surface: { + description: 'Light surface theme', + toolbar: { + dynamicTitle: true, + icon: 'paintbrush', + items: [ + { title: 'Paper', value: SurfaceTheme.PAPER }, + { title: 'Matte', value: SurfaceTheme.MATTE } + ], + title: 'Surface' + } + } + }, + initialGlobals: { + interactionPace: 'human', + surface: SurfaceTheme.PAPER + }, + decorators: [ + (story, context) => { + applySurfaceTheme(context.globals.surface); + + return story(); + }, + // `parameters.colorScheme` fixes a story to light or dark, whatever the viewer chose (a scene in a store screenshot) + (story, context) => ({ + Component: ModeWatcherDecorator, + props: { + children: story, + forced: context.parameters.colorScheme + } + }), + (story) => ({ + Component: TooltipProviderDecorator, + props: { + children: story + } + }) + ] +}; + +export default preview; diff --git a/ui/apps/chat/AGENTS.md b/ui/apps/chat/AGENTS.md new file mode 100644 index 000000000000..32e6a009a2c9 --- /dev/null +++ b/ui/apps/chat/AGENTS.md @@ -0,0 +1,23 @@ +# Instructions for ui/apps/chat + +These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/apps/chat`: **Llama Chat**, the chat client that llama-server bundles. **Llama UI**, the library, is `ui/lib/ui` (`@ggml-org/llama-ui`): Chat imports its tokens, fonts and base components from there (`@ggml-org/llama-ui/ui/`) and keeps no copy of them. `DESIGN.md` and the Storybook live here; the brand book, `BRAND.md`, and the brand and communications pages are in [ggml-org/llama-brand](https://github.com/ggml-org/llama-brand), with their own Storybook. + +- **Design:** [DESIGN.md](DESIGN.md) holds the tokens, roles and rules, written for agents. Follow it for anything visual. Its token sections (`colors`, `typography`, `rounded`) are generated from the CSS with `npm run design:tokens`, and CI checks they are current; the rest is written by hand, and when it and the CSS disagree, the CSS wins and DESIGN.md is updated. +- **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/`, one folder per `src/lib/components/app/` (`chat/` has one per Chat folder), titled `Llama Chat//`. An accessibility story sits next to its component's, as `.a11y.stories.svelte`, titled `...//Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here. +- **Releases:** `@ggml-org/llama-chat` and `@ggml-org/llama-ui` are versioned by hand and published by CI when a new version reaches `master` (see [Releases](../../README.md#releases)). Bump a version only when asked to release, never as a side effect of a change; Chat's version and its alias's (`alias/package.json`) always move together. +- **Components:** the `SKILL.md` next to a component folder (such as [src/lib/components/app/SKILL.md](src/lib/components/app/SKILL.md)) holds that folder's conventions. + +## Content is Markdown, custom pieces are Svelte: .svx + +Anything that is mostly content (a doc, an overview, a showcase or a Storybook page with prose) is written in Markdown, and whatever Markdown cannot express (a live example, a diagram, a real component) is a Svelte component placed in it. Together that is a `.svx` page, compiled by [mdsvex](https://mdsvex.pngwk.com). + +- Write the prose as plain Markdown, so it reads well as source, for people and for agents alike. +- Put each custom piece in its own `.svelte` file and import it in the page's ` + + diff --git a/tools/ui/src/lib/components/app/actions/GlassKey.svelte b/ui/apps/chat/src/lib/components/app/actions/GlassKey.svelte similarity index 72% rename from tools/ui/src/lib/components/app/actions/GlassKey.svelte rename to ui/apps/chat/src/lib/components/app/actions/GlassKey.svelte index b2ccffe6a16b..d4a30779932e 100644 --- a/tools/ui/src/lib/components/app/actions/GlassKey.svelte +++ b/ui/apps/chat/src/lib/components/app/actions/GlassKey.svelte @@ -1,6 +1,7 @@ {#if deviceStore.isMobile} diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte similarity index 81% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte index 9571045c544a..04fd275fd590 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte @@ -1,14 +1,14 @@ + +{#snippet dial(size: 'sm' | 'md' | 'key')} + +{/snippet} + +{#if corner} + + + {@render dial('key')} + +{:else} +
+ + {@render dial(deviceStore.isMobile ? 'md' : 'sm')} +
+{/if} diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetailRow.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetailRow.svelte similarity index 100% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetailRow.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetailRow.svelte diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte similarity index 98% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte index 34cf3d0bc484..f57dcc636e2d 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte @@ -1,6 +1,6 @@
- + {#if showTooltip && displayLabelTitle} @@ -58,10 +60,10 @@ > + import { cn } from '@ggml-org/llama-ui/utils'; import { Folder } from '@lucide/svelte'; - import { cn } from '$lib/components/ui/utils'; - import { UI_DATA_ATTRS } from '$lib/constants'; - import { highlightMatch } from '$lib/utils'; + import { UI_DATA_ATTRS } from '#lib/constants/index.ts'; + import { highlightMatch } from '#lib/utils/index.ts'; import { fly } from 'svelte/transition'; // Fly-in transition for the results list. diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormInput/ChatFormInput.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormInput/ChatFormInput.svelte similarity index 90% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormInput/ChatFormInput.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormInput/ChatFormInput.svelte index 540a344dac7c..06a456a41690 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormInput/ChatFormInput.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormInput/ChatFormInput.svelte @@ -1,11 +1,11 @@
- + {#if showSpinner} Current time - + {:else if dateMeta.errorMessage} Current time  - - {dateMeta.errorMessage} + - {dateMeta.errorMessage} {:else if dateMeta.dateString} Current time is  diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte similarity index 90% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte index 225d9def90a4..5459210654a4 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte @@ -1,9 +1,9 @@ -
+
diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte similarity index 92% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte index f79d2604b1b1..68be708ed9cd 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte @@ -1,7 +1,7 @@ + + diff --git a/tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte similarity index 90% rename from tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte index d8ff0d2eee8c..5dc6107a0dde 100644 --- a/tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte @@ -4,8 +4,8 @@ DialogConversationDelete, DialogEmptyFileAlert, DialogFileUploadError - } from '$lib/components/app'; - import { ErrorDialogType } from '$lib/enums'; + } from '#lib/components/app/index.ts'; + import { ErrorDialogType } from '#lib/enums/index.ts'; let { activeErrorDialog, diff --git a/tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenDragOverlay.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDragOverlay.svelte similarity index 74% rename from tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenDragOverlay.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDragOverlay.svelte index ab4adb2c2922..c3ae91a2f28f 100644 --- a/tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenDragOverlay.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDragOverlay.svelte @@ -6,9 +6,9 @@ class="pointer-events-none fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm" >
- +

Attach a file

diff --git a/tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte similarity index 93% rename from tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte index fe382bd071f1..309cb722289a 100644 --- a/tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte @@ -1,11 +1,11 @@ @@ -12,7 +12,7 @@ class="pointer-events-auto mx-auto mt-2 mb-2 flex max-w-[48rem] items-center gap-2 rounded-md border border-blue-400/40 bg-blue-50/60 px-3 py-1.5 text-sm text-blue-700 dark:bg-blue-950/40 dark:text-blue-200" role="status" > - + Reconnecting to the stream...
diff --git a/tools/ui/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte similarity index 93% rename from tools/ui/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte index 515bf4f78cf7..c4a68a2dbfc8 100644 --- a/tools/ui/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte @@ -2,8 +2,7 @@ import ChatTabsItem from './ChatTabsItem.svelte'; import ChatTabsNewChatButton from './ChatTabsNewChatButton.svelte'; import { ArrowRightToLine, ListX, Square, SquarePen, X } from '@lucide/svelte'; - import { page } from '$app/state'; - import { ContextMenuActions, ScrollCarousel } from '$lib/components/app'; + import { ContextMenuActions, ScrollCarousel } from '#lib/components/app/index.ts'; import { CHAT_TABS_MAX_WIDTH, NEW_CHAT_LABEL, @@ -11,11 +10,12 @@ SHORTCUT_CLOSE_TAB, UI_DATA_ATTRS, UNNAMED_CHAT_LABEL - } from '$lib/constants'; - import { useScrollCarousel } from '$lib/hooks/use-scroll-carousel.svelte'; - import { chatStore, conversationsStore, tabsStore, uiStore } from '$lib/stores'; - import type { MenuAction } from '$lib/types'; - import { resolveTabView } from '$lib/utils'; + } from '#lib/constants/index.ts'; + import { useScrollCarousel } from '#lib/hooks/use-scroll-carousel.svelte.ts'; + import { chatStore, conversationsStore, tabsStore, uiStore } from '#lib/stores/index.ts'; + import type { MenuAction } from '#lib/types/index.ts'; + import { resolveTabView } from '#lib/utils/index.ts'; + import { page } from '$app/state'; import { tick } from 'svelte'; const carousel = useScrollCarousel(); diff --git a/tools/ui/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte similarity index 88% rename from tools/ui/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte index d161f0f1d770..c01af20d6f4b 100644 --- a/tools/ui/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte @@ -1,7 +1,7 @@
-
diff --git a/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardCompact.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardCompact.svelte similarity index 87% rename from tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardCompact.svelte rename to ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardCompact.svelte index da0ce1ffe75f..4abd93ed01b5 100644 --- a/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardCompact.svelte +++ b/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardCompact.svelte @@ -1,6 +1,6 @@
- + @@ -33,10 +33,10 @@
- + - + - +
diff --git a/tools/ui/src/lib/components/app/mcp/McpServerForm.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpServerForm.svelte similarity index 94% rename from tools/ui/src/lib/components/app/mcp/McpServerForm.svelte rename to ui/apps/chat/src/lib/components/app/mcp/McpServerForm.svelte index f9f07ad63d9e..c0dd254e76a4 100644 --- a/tools/ui/src/lib/components/app/mcp/McpServerForm.svelte +++ b/ui/apps/chat/src/lib/components/app/mcp/McpServerForm.svelte @@ -1,12 +1,12 @@ - (isNearViewport = true)} class={className}> + (isNearViewport = true))} class={className}> - import { MODEL_ID } from '$lib/constants'; - import { HuggingFaceService } from '$lib/services'; - import type { ModelOption } from '$lib/types/models'; - import { nearViewport, repoOf } from '$lib/utils'; - import { formatContextLength } from '$lib/utils/formatters'; + import { MODEL_ID } from '#lib/constants/index.ts'; + import { HuggingFaceService } from '#lib/services/index.ts'; + import type { ModelOption } from '#lib/types/models.js'; + import { formatContextLength } from '#lib/utils/formatters.ts'; + import { nearViewport, repoOf } from '#lib/utils/index.ts'; interface Props { class?: string; @@ -51,7 +51,7 @@ (isNearViewport = true)} + {@attach nearViewport(() => (isNearViewport = true))} class={['text-sm text-muted-foreground', className]} > {formatContextLength(values)} diff --git a/tools/ui/src/lib/components/app/models/ModelDraftSubline.svelte b/ui/apps/chat/src/lib/components/app/models/ModelDraftSubline.svelte similarity index 88% rename from tools/ui/src/lib/components/app/models/ModelDraftSubline.svelte rename to ui/apps/chat/src/lib/components/app/models/ModelDraftSubline.svelte index 101215d11138..9d308c0bb44c 100644 --- a/tools/ui/src/lib/components/app/models/ModelDraftSubline.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelDraftSubline.svelte @@ -1,7 +1,7 @@ + +{#if resolvedShowRaw} + +{:else} + !isAuxSidecar(badge.kind))} + name={parsed.modelName ?? modelId} + org={parsed.orgName ?? undefined} + params={hideParameters ? undefined : (parsed.params ?? undefined)} + quantization={resolvedHideQuantization ? undefined : (parsed.quantization ?? undefined)} + sidecar={parsed.sidecar ?? undefined} + tags={resolvedHideTags ? [] : [...(parsed.tags ?? []), ...(tags ?? [])]} + tooltip={showRawTooltip ? modelId : undefined} + /> +{/if} diff --git a/tools/ui/src/lib/components/app/models/ModelLoadControl.svelte b/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte similarity index 69% rename from tools/ui/src/lib/components/app/models/ModelLoadControl.svelte rename to ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte index 6d1ea5a93e60..4c54d751cac4 100644 --- a/tools/ui/src/lib/components/app/models/ModelLoadControl.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte @@ -1,8 +1,8 @@ + +{#if hubEnabled} + +{/if} diff --git a/tools/ui/src/lib/components/app/models/ModelRowActions.svelte b/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte similarity index 76% rename from tools/ui/src/lib/components/app/models/ModelRowActions.svelte rename to ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte index 5c2f321bd2df..33be4c624d35 100644 --- a/tools/ui/src/lib/components/app/models/ModelRowActions.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte @@ -1,8 +1,8 @@ {#snippet selectorTriggerInner()} - + {#if selectedOption} @@ -154,9 +154,9 @@ ms.setSearchTerm(v)} {onSearchKeyDown} @@ -204,20 +205,21 @@ {@render pickerContent('px-1.5')} - - {#snippet footer()} - - - - - Manage models - - - {/snippet} + +{#snippet manageModelsFooter()} + + + + + Manage models + + +{/snippet} + {#snippet pickerContent(listClass: string)}
{#if !ms.isCurrentModelInCache && currentModel} @@ -225,7 +227,7 @@
diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsDownloadOptions/ModelsDiscoverDetailsDownloadOptionsDraftDownloadButton.svelte b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsDownloadOptions/ModelsDiscoverDetailsDownloadOptionsDraftDownloadButton.svelte similarity index 73% rename from tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsDownloadOptions/ModelsDiscoverDetailsDownloadOptionsDraftDownloadButton.svelte rename to ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsDownloadOptions/ModelsDiscoverDetailsDownloadOptionsDraftDownloadButton.svelte index d7cbd8becd84..2ba973c2cb92 100644 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsDownloadOptions/ModelsDiscoverDetailsDownloadOptionsDraftDownloadButton.svelte +++ b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsDownloadOptions/ModelsDiscoverDetailsDownloadOptionsDraftDownloadButton.svelte @@ -1,9 +1,9 @@ {#if readme} -
+
{/if} diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsSkeleton.svelte b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsSkeleton.svelte similarity index 89% rename from tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsSkeleton.svelte rename to ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsSkeleton.svelte index 8438a3c2b47d..1841495389d4 100644 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsSkeleton.svelte +++ b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsSkeleton.svelte @@ -1,5 +1,5 @@ @@ -8,7 +8,7 @@
- +
@@ -47,7 +47,7 @@
-
+
{#each [0, 1, 2] as _, index (index)}
-
+
diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/index.ts b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/index.ts similarity index 100% rename from tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/index.ts rename to ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/index.ts diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverList/ModelsDiscoverList.svelte b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverList/ModelsDiscoverList.svelte similarity index 93% rename from tools/ui/src/lib/components/app/models/discover/ModelsDiscoverList/ModelsDiscoverList.svelte rename to ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverList/ModelsDiscoverList.svelte index 5ebff7230d32..8f6c41345fe2 100644 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverList/ModelsDiscoverList.svelte +++ b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverList/ModelsDiscoverList.svelte @@ -1,7 +1,7 @@ -
+
section.slug === activeSlug} @@ -190,7 +199,7 @@
diff --git a/tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte similarity index 83% rename from tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte rename to ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte index 528654ee580e..4dc97756d7fa 100644 --- a/tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte @@ -1,16 +1,21 @@ diff --git a/tools/ui/src/lib/components/pwa/PwaRefreshAlert.svelte b/ui/apps/chat/src/lib/components/pwa/PwaRefreshAlert.svelte similarity index 67% rename from tools/ui/src/lib/components/pwa/PwaRefreshAlert.svelte rename to ui/apps/chat/src/lib/components/pwa/PwaRefreshAlert.svelte index 56a71406ff6b..00cde3c6ba6e 100644 --- a/tools/ui/src/lib/components/pwa/PwaRefreshAlert.svelte +++ b/ui/apps/chat/src/lib/components/pwa/PwaRefreshAlert.svelte @@ -1,8 +1,8 @@ @@ -18,12 +18,7 @@ + + + Downloaded + + +
+
diff --git a/ui/lib/ui/src/svelte.config.js b/ui/lib/ui/src/svelte.config.js new file mode 100644 index 000000000000..e0d56086c001 --- /dev/null +++ b/ui/lib/ui/src/svelte.config.js @@ -0,0 +1,5 @@ +// Apps in ui/apps compile these sources themselves, so their svelte-check and editors read +// them too and look upwards from each file for a Svelte config. Without this one they would +// load vite.config.ts a level up, which needs this package's own dependencies installed. +// The package itself is configured in vite.config.ts. +export default {}; diff --git a/ui/lib/ui/static/favicon.ico b/ui/lib/ui/static/favicon.ico new file mode 100644 index 000000000000..4d5fa4cdddcf Binary files /dev/null and b/ui/lib/ui/static/favicon.ico differ diff --git a/ui/lib/ui/static/favicon.svg b/ui/lib/ui/static/favicon.svg new file mode 100644 index 000000000000..e15ac3d7675c --- /dev/null +++ b/ui/lib/ui/static/favicon.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/tools/ui/tests/stories/a11y/ActionIcon.a11y.stories.svelte b/ui/lib/ui/tests/stories/app/ActionIcon.a11y.stories.svelte similarity index 85% rename from tools/ui/tests/stories/a11y/ActionIcon.a11y.stories.svelte rename to ui/lib/ui/tests/stories/app/ActionIcon.a11y.stories.svelte index f94e7a792bea..2a0635015db2 100644 --- a/tools/ui/tests/stories/a11y/ActionIcon.a11y.stories.svelte +++ b/ui/lib/ui/tests/stories/app/ActionIcon.a11y.stories.svelte @@ -1,7 +1,7 @@ diff --git a/ui/lib/ui/tests/stories/app/ActionIcon.stories.svelte b/ui/lib/ui/tests/stories/app/ActionIcon.stories.svelte new file mode 100644 index 000000000000..ee3b1a62f6e4 --- /dev/null +++ b/ui/lib/ui/tests/stories/app/ActionIcon.stories.svelte @@ -0,0 +1,34 @@ + + + + + +
+ + + + + +
+
+ + + + +
+
diff --git a/ui/lib/ui/tests/stories/app/SearchInput.stories.svelte b/ui/lib/ui/tests/stories/app/SearchInput.stories.svelte new file mode 100644 index 000000000000..13db4d2be05c --- /dev/null +++ b/ui/lib/ui/tests/stories/app/SearchInput.stories.svelte @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + diff --git a/ui/lib/ui/tests/stories/app/SyntaxHighlightedCode.stories.svelte b/ui/lib/ui/tests/stories/app/SyntaxHighlightedCode.stories.svelte new file mode 100644 index 000000000000..e3bd6cc2abc2 --- /dev/null +++ b/ui/lib/ui/tests/stories/app/SyntaxHighlightedCode.stories.svelte @@ -0,0 +1,23 @@ + + + diff --git a/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte b/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte new file mode 100644 index 000000000000..bbabfd5a03e8 --- /dev/null +++ b/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte @@ -0,0 +1,54 @@ + + + + + {#each variants as variant (variant)} + +
+ {#each sizes as size (size)} + + {/each} + + + + +
+
+ {/each} + + +
+ + + +
+
+
+
diff --git a/ui/lib/ui/tests/stories/components/actions/ButtonGroup.stories.svelte b/ui/lib/ui/tests/stories/components/actions/ButtonGroup.stories.svelte new file mode 100644 index 000000000000..9704b419c532 --- /dev/null +++ b/ui/lib/ui/tests/stories/components/actions/ButtonGroup.stories.svelte @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ui/lib/ui/tests/stories/components/actions/Toggle.stories.svelte b/ui/lib/ui/tests/stories/components/actions/Toggle.stories.svelte new file mode 100644 index 000000000000..15594608f33e --- /dev/null +++ b/ui/lib/ui/tests/stories/components/actions/Toggle.stories.svelte @@ -0,0 +1,66 @@ + + + + + + + + + + + + + +
+ + + +
+
+ + +
+ Wrap + + Wrap + + Wrap +
+
+ + + + + + +
+ + + Toggle + + + + Wrap + + + + +
+
+
+
diff --git a/ui/lib/ui/tests/stories/components/actions/ToggleGroup.stories.svelte b/ui/lib/ui/tests/stories/components/actions/ToggleGroup.stories.svelte new file mode 100644 index 000000000000..73eabcf47ffb --- /dev/null +++ b/ui/lib/ui/tests/stories/components/actions/ToggleGroup.stories.svelte @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + Tools + + Vision + + Audio + + + + + + Tools + + Vision + + Audio + + + + +
+ {#each sizes as size (size)} + + + + + + {/each} +
+
+ + + + + + + + +
+
diff --git a/ui/lib/ui/tests/stories/components/display/Alert.stories.svelte b/ui/lib/ui/tests/stories/components/display/Alert.stories.svelte new file mode 100644 index 000000000000..85e7ca7cb604 --- /dev/null +++ b/ui/lib/ui/tests/stories/components/display/Alert.stories.svelte @@ -0,0 +1,77 @@ + + + + + + + + + Model is loading + + The first reply can take a few seconds. + + + + + + + + Context is full + + Start a new chat or remove some attachments. + + + + + + + + Model loaded + + Qwen 2.5 7B is ready on port 9931. + + + + + + + + Low memory + + Gemma 2 27B needs 16.6 GB; 12 GB is free. + + + + + + + + Update available + + llama.cpp b9726 adds faster prompt processing. + + + + + + + + Saved to this browser + + + + diff --git a/ui/lib/ui/tests/stories/components/display/Badge.stories.svelte b/ui/lib/ui/tests/stories/components/display/Badge.stories.svelte new file mode 100644 index 000000000000..86862b0fa17d --- /dev/null +++ b/ui/lib/ui/tests/stories/components/display/Badge.stories.svelte @@ -0,0 +1,35 @@ + + + + + {#each variants as variant (variant)} + + Q4_K_M + + {/each} + + diff --git a/ui/lib/ui/tests/stories/components/display/Card.stories.svelte b/ui/lib/ui/tests/stories/components/display/Card.stories.svelte new file mode 100644 index 000000000000..3119820d4c18 --- /dev/null +++ b/ui/lib/ui/tests/stories/components/display/Card.stories.svelte @@ -0,0 +1,33 @@ + + + + + + Qwen3.8-27B + + 131k context, vision and tool use + + + + Loaded on the server and ready to answer. + + + + + + + + + diff --git a/ui/lib/ui/tests/stories/components/display/Collapsible.stories.svelte b/ui/lib/ui/tests/stories/components/display/Collapsible.stories.svelte new file mode 100644 index 000000000000..2546c3c2ad22 --- /dev/null +++ b/ui/lib/ui/tests/stories/components/display/Collapsible.stories.svelte @@ -0,0 +1,52 @@ + + +{#snippet section(open: boolean)} + +
+ Advanced sampling + + + {#snippet child({ props })} + + {/snippet} + +
+ +
temperature 0.8
+ + +
top_p 0.95
+ +
min_p 0.05
+
+
+{/snippet} + + + + + {@render section(false)} + + + + {@render section(true)} + + + diff --git a/ui/lib/ui/tests/stories/components/display/Empty.stories.svelte b/ui/lib/ui/tests/stories/components/display/Empty.stories.svelte new file mode 100644 index 000000000000..4e24b3fc82cd --- /dev/null +++ b/ui/lib/ui/tests/stories/components/display/Empty.stories.svelte @@ -0,0 +1,32 @@ + + + + + + + + + + No conversations yet + + Your chats are saved in this browser and show up here. + + + + + + + diff --git a/ui/lib/ui/tests/stories/components/display/ScrollArea.stories.svelte b/ui/lib/ui/tests/stories/components/display/ScrollArea.stories.svelte new file mode 100644 index 000000000000..5f352b904353 --- /dev/null +++ b/ui/lib/ui/tests/stories/components/display/ScrollArea.stories.svelte @@ -0,0 +1,29 @@ + + + + +
+

Conversations

+ + {#each chats as chat (chat)} +
{chat}
+ + + {/each} +
+
+
diff --git a/ui/lib/ui/tests/stories/components/display/Separator.stories.svelte b/ui/lib/ui/tests/stories/components/display/Separator.stories.svelte new file mode 100644 index 000000000000..8a659c0d9975 --- /dev/null +++ b/ui/lib/ui/tests/stories/components/display/Separator.stories.svelte @@ -0,0 +1,34 @@ + + + +
+

Qwen3.8-27B

+ +

Loaded, 131k context

+ + + +
+ Chat + + + + Models + + + + Settings +
+
+
diff --git a/ui/lib/ui/tests/stories/components/display/Skeleton.stories.svelte b/ui/lib/ui/tests/stories/components/display/Skeleton.stories.svelte new file mode 100644 index 000000000000..ae2dba5ffb2d --- /dev/null +++ b/ui/lib/ui/tests/stories/components/display/Skeleton.stories.svelte @@ -0,0 +1,40 @@ + + + + + +
+ + + + + +
+
+ + +
+ + +
+ + + +
+
+
+
+
diff --git a/ui/lib/ui/tests/stories/components/display/Table.stories.svelte b/ui/lib/ui/tests/stories/components/display/Table.stories.svelte new file mode 100644 index 000000000000..d253cc53a620 --- /dev/null +++ b/ui/lib/ui/tests/stories/components/display/Table.stories.svelte @@ -0,0 +1,60 @@ + + + +
+ + Models on this server + + + + Model + + Quant + + Context + + Size + + + + + {#each rows as row (row.model + row.quant)} + + {row.model} + + {row.quant} + + {row.context} + + {row.size} + + {/each} + + + + + Total + + 47.1 GB + + + +
+
diff --git a/ui/lib/ui/tests/stories/components/forms/Checkbox.stories.svelte b/ui/lib/ui/tests/stories/components/forms/Checkbox.stories.svelte new file mode 100644 index 000000000000..a091f067558d --- /dev/null +++ b/ui/lib/ui/tests/stories/components/forms/Checkbox.stories.svelte @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ui/lib/ui/tests/stories/components/forms/Input.stories.svelte b/ui/lib/ui/tests/stories/components/forms/Input.stories.svelte new file mode 100644 index 000000000000..14404c5a9930 --- /dev/null +++ b/ui/lib/ui/tests/stories/components/forms/Input.stories.svelte @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ui/lib/ui/tests/stories/components/forms/Label.stories.svelte b/ui/lib/ui/tests/stories/components/forms/Label.stories.svelte new file mode 100644 index 000000000000..dcf3a927d6ae --- /dev/null +++ b/ui/lib/ui/tests/stories/components/forms/Label.stories.svelte @@ -0,0 +1,21 @@ + + + +
+ + + +
+
diff --git a/ui/lib/ui/tests/stories/components/forms/RadioGroup.stories.svelte b/ui/lib/ui/tests/stories/components/forms/RadioGroup.stories.svelte new file mode 100644 index 000000000000..1e31f12689bd --- /dev/null +++ b/ui/lib/ui/tests/stories/components/forms/RadioGroup.stories.svelte @@ -0,0 +1,43 @@ + + + + + + + {#each options as option (option)} + + {/each} + + + + + + {#each options as option (option)} + + {/each} + + + + diff --git a/ui/lib/ui/tests/stories/components/forms/Select.stories.svelte b/ui/lib/ui/tests/stories/components/forms/Select.stories.svelte new file mode 100644 index 000000000000..bd3e1743263b --- /dev/null +++ b/ui/lib/ui/tests/stories/components/forms/Select.stories.svelte @@ -0,0 +1,60 @@ + + + + + + + Choose a theme + + + + + + Dark + + + + + + System + + + + +
+ + Light + + + + Theme + + {#each themes as theme (theme.value)} + + {/each} + + + +
+
+
+
diff --git a/ui/lib/ui/tests/stories/components/forms/Switch.stories.svelte b/ui/lib/ui/tests/stories/components/forms/Switch.stories.svelte new file mode 100644 index 000000000000..c9cb3453ff79 --- /dev/null +++ b/ui/lib/ui/tests/stories/components/forms/Switch.stories.svelte @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/ui/lib/ui/tests/stories/components/forms/Textarea.stories.svelte b/ui/lib/ui/tests/stories/components/forms/Textarea.stories.svelte new file mode 100644 index 000000000000..779c152223e8 --- /dev/null +++ b/ui/lib/ui/tests/stories/components/forms/Textarea.stories.svelte @@ -0,0 +1,34 @@ + + + + + +