mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-23 03:07:37 -06:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63fd885b6f | ||
|
|
e5554b975d |
@@ -19,16 +19,12 @@ FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
WORKDIR /app/tools/ui
|
||||
|
||||
COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
COPY tools/ui/package.json tools/ui/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI and Llama Voice from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY tools/ui/ ./
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM ${CANN_BASE_IMAGE} AS build
|
||||
@@ -44,7 +40,7 @@ WORKDIR /app
|
||||
# -- Copy project files --
|
||||
COPY . .
|
||||
|
||||
COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist
|
||||
COPY --from=web /app/tools/ui/dist tools/ui/dist
|
||||
|
||||
# -- Set CANN environment variables (required for compilation) --
|
||||
# Using ENV instead of `source` allows environment variables to persist across the entire image layer
|
||||
|
||||
@@ -9,16 +9,12 @@ FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
WORKDIR /app/tools/ui
|
||||
|
||||
COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
COPY tools/ui/package.json tools/ui/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI and Llama Voice from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY tools/ui/ ./
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
|
||||
@@ -32,7 +28,7 @@ WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist
|
||||
COPY --from=web /app/tools/ui/dist tools/ui/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; \
|
||||
|
||||
@@ -17,16 +17,12 @@ FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
WORKDIR /app/tools/ui
|
||||
|
||||
COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
COPY tools/ui/package.json tools/ui/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI and Llama Voice from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY tools/ui/ ./
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM ${BASE_CUDA_DEV_CONTAINER} AS build
|
||||
@@ -44,7 +40,7 @@ WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist
|
||||
COPY --from=web /app/tools/ui/dist tools/ui/dist
|
||||
|
||||
RUN if [ "${CUDA_DOCKER_ARCH}" != "default" ]; then \
|
||||
export CMAKE_ARGS="-DCMAKE_CUDA_ARCHITECTURES=${CUDA_DOCKER_ARCH}"; \
|
||||
|
||||
@@ -11,16 +11,12 @@ FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
WORKDIR /app/tools/ui
|
||||
|
||||
COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
COPY tools/ui/package.json tools/ui/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI and Llama Voice from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY tools/ui/ ./
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM docker.io/intel/deep-learning-essentials:$ONEAPI_VERSION AS build
|
||||
@@ -45,7 +41,7 @@ WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist
|
||||
COPY --from=web /app/tools/ui/dist tools/ui/dist
|
||||
|
||||
RUN if [ "${GGML_SYCL_F16}" = "ON" ]; then \
|
||||
echo "GGML_SYCL_F16 is set" \
|
||||
|
||||
@@ -15,16 +15,12 @@ FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
WORKDIR /app/tools/ui
|
||||
|
||||
COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
COPY tools/ui/package.json tools/ui/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI and Llama Voice from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY tools/ui/ ./
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM ${BASE_MUSA_DEV_CONTAINER} AS build
|
||||
@@ -49,7 +45,7 @@ WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist
|
||||
COPY --from=web /app/tools/ui/dist tools/ui/dist
|
||||
|
||||
RUN if [ "${MUSA_DOCKER_ARCH}" != "default" ]; then \
|
||||
export CMAKE_ARGS="-DMUSA_ARCHITECTURES=${MUSA_DOCKER_ARCH}"; \
|
||||
|
||||
+41
-138
@@ -22,19 +22,12 @@
|
||||
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,
|
||||
@@ -45,28 +38,11 @@
|
||||
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
|
||||
|
||||
# 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,
|
||||
# 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,
|
||||
enableStatic ? effectiveStdenv.hostPlatform.isStatic,
|
||||
precompileMetalShaders ? false,
|
||||
useWebUi ? true,
|
||||
@@ -89,8 +65,7 @@ let
|
||||
++ lib.optionals useMetalKit [ "MetalKit" ]
|
||||
++ lib.optionals useMpi [ "MPI" ]
|
||||
++ lib.optionals useRocm [ "ROCm" ]
|
||||
++ lib.optionals useVulkan [ "Vulkan" ]
|
||||
++ lib.optionals useSycl [ "SYCL" ];
|
||||
++ lib.optionals useVulkan [ "Vulkan" ];
|
||||
|
||||
pnameSuffix =
|
||||
strings.optionalString (suffices != [ ])
|
||||
@@ -133,26 +108,6 @@ 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: {
|
||||
@@ -178,13 +133,11 @@ effectiveStdenv.mkDerivation (finalAttrs: {
|
||||
src = lib.cleanSource ../../.;
|
||||
};
|
||||
|
||||
# Builds Llama Chat locally, taking care not to require updating any sha256 hash.
|
||||
# Builds the webui locally, taking care not to require updating any sha256 hash.
|
||||
webui = stdenvNoCC.mkDerivation {
|
||||
pname = "webui";
|
||||
version = llamaVersion;
|
||||
# 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";
|
||||
src = lib.cleanSource ../../tools/ui;
|
||||
|
||||
nativeBuildInputs = [
|
||||
nodejs
|
||||
@@ -193,7 +146,7 @@ effectiveStdenv.mkDerivation (finalAttrs: {
|
||||
|
||||
# no sha256 required when using buildNodeModules
|
||||
npmDeps = importNpmLock.buildNodeModules {
|
||||
npmRoot = ../../ui/apps/chat;
|
||||
npmRoot = ../../tools/ui;
|
||||
inherit nodejs;
|
||||
};
|
||||
|
||||
@@ -203,8 +156,8 @@ effectiveStdenv.mkDerivation (finalAttrs: {
|
||||
};
|
||||
|
||||
postPatch = lib.optionalString useWebUi ''
|
||||
cp -r ${finalAttrs.webui} ui/apps/chat/dist
|
||||
chmod -R u+w ui/apps/chat/dist
|
||||
cp -r ${finalAttrs.webui} tools/ui/dist
|
||||
chmod -R u+w tools/ui/dist
|
||||
'';
|
||||
|
||||
# With PR#6015 https://github.com/ggml-org/llama.cpp/pull/6015,
|
||||
@@ -215,13 +168,6 @@ 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
|
||||
@@ -235,12 +181,7 @@ effectiveStdenv.mkDerivation (finalAttrs: {
|
||||
autoAddDriverRunpath
|
||||
]
|
||||
++ optionals (effectiveStdenv.hostPlatform.isGnu && enableStatic) [ glibc.static ]
|
||||
++ optionals (effectiveStdenv.hostPlatform.isDarwin && useMetalKit && precompileMetalShaders) [ xcrunHost ]
|
||||
++ optionals useSycl [
|
||||
autoAddDriverRunpath
|
||||
makeBinaryWrapper
|
||||
]
|
||||
++ optionals syclAot [ oclocAot ];
|
||||
++ optionals (effectiveStdenv.hostPlatform.isDarwin && useMetalKit && precompileMetalShaders) [ xcrunHost ];
|
||||
|
||||
buildInputs =
|
||||
optionals effectiveStdenv.hostPlatform.isDarwin darwinBuildInputs
|
||||
@@ -249,53 +190,39 @@ 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 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))
|
||||
];
|
||||
]
|
||||
++ 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))
|
||||
];
|
||||
|
||||
# Environment variables needed for ROCm
|
||||
env = optionalAttrs useRocm {
|
||||
@@ -310,35 +237,11 @@ 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
|
||||
++ optionals useSycl (lib.subtractLists [ "x86_64-linux" ] lib.platforms.all);
|
||||
badPlatforms = optionals useCuda lib.platforms.darwin;
|
||||
|
||||
# Configurations that are known to result in build failures. Can be
|
||||
# overridden by importing Nixpkgs with `allowBroken = true`.
|
||||
|
||||
@@ -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.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
|
||||
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
|
||||
|
||||
# Intel NPU driver versions. https://github.com/intel/linux-npu-driver/releases
|
||||
ARG NPU_DRIVER_VERSION=v1.38.0
|
||||
@@ -28,16 +28,12 @@ FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
WORKDIR /app/tools/ui
|
||||
|
||||
COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
COPY tools/ui/package.json tools/ui/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI and Llama Voice from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY tools/ui/ ./
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
## Build Image
|
||||
@@ -87,7 +83,7 @@ WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist
|
||||
COPY --from=web /app/tools/ui/dist tools/ui/dist
|
||||
|
||||
# Build Stage
|
||||
RUN bash -c "source ${OpenVINO_DIR}/setupvars.sh && \
|
||||
|
||||
@@ -17,16 +17,12 @@ FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
WORKDIR /app/tools/ui
|
||||
|
||||
COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
COPY tools/ui/package.json tools/ui/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI and Llama Voice from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY tools/ui/ ./
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
### Build image
|
||||
@@ -56,7 +52,7 @@ WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist
|
||||
COPY --from=web /app/tools/ui/dist tools/ui/dist
|
||||
|
||||
RUN HIPCXX="$(hipconfig -l)/clang" HIP_PATH="$(hipconfig -R)" \
|
||||
cmake -S . -B build \
|
||||
|
||||
@@ -9,16 +9,12 @@ FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
WORKDIR /app/tools/ui
|
||||
|
||||
COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
COPY tools/ui/package.json tools/ui/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI and Llama Voice from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY tools/ui/ ./
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
|
||||
@@ -35,7 +31,7 @@ WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist
|
||||
COPY --from=web /app/tools/ui/dist tools/ui/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)
|
||||
|
||||
@@ -9,16 +9,12 @@ FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
WORKDIR /app/tools/ui
|
||||
|
||||
COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
COPY tools/ui/package.json tools/ui/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI and Llama Voice from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY tools/ui/ ./
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
|
||||
@@ -32,7 +28,7 @@ WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist
|
||||
COPY --from=web /app/tools/ui/dist tools/ui/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)
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
|
||||
build*/
|
||||
|
||||
ui/apps/chat/node_modules/
|
||||
tools/ui/node_modules/
|
||||
|
||||
models/*
|
||||
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ insert_final_newline = unset
|
||||
[vendor/**.patch]
|
||||
trim_trailing_whitespace = unset
|
||||
|
||||
[ui/**]
|
||||
[tools/ui/**]
|
||||
indent_style = unset
|
||||
indent_size = unset
|
||||
end_of_line = unset
|
||||
|
||||
@@ -14,9 +14,7 @@ runs:
|
||||
run: |
|
||||
BUILD_NUMBER="$(git rev-list --count HEAD)"
|
||||
SHORT_HASH="$(git rev-parse --short=7 HEAD)"
|
||||
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
|
||||
if [[ "${{ 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 '/' '-')
|
||||
|
||||
@@ -25,9 +25,7 @@ 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
|
||||
@@ -56,9 +54,7 @@ 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
|
||||
@@ -89,9 +85,7 @@ 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
|
||||
@@ -122,9 +116,7 @@ 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
|
||||
@@ -151,9 +143,7 @@ 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
|
||||
|
||||
+2
-1
@@ -48,6 +48,7 @@ examples:
|
||||
- all-globs-to-all-files:
|
||||
- '!tools/server/**'
|
||||
- '!tools/mtmd/**'
|
||||
- '!tools/ui/**'
|
||||
testing:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
@@ -71,7 +72,7 @@ android:
|
||||
server/ui:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- ui/**
|
||||
- tools/ui/**
|
||||
server:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
|
||||
@@ -140,11 +140,6 @@ 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
|
||||
|
||||
@@ -187,11 +187,6 @@ 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: |
|
||||
|
||||
@@ -98,7 +98,7 @@ jobs:
|
||||
|
||||
hip:
|
||||
runs-on: ubuntu-22.04
|
||||
container: rocm/dev-ubuntu-22.04:6.3.4
|
||||
container: rocm/dev-ubuntu-22.04:6.1.2
|
||||
|
||||
steps:
|
||||
- name: Clone
|
||||
|
||||
@@ -137,8 +137,8 @@ jobs:
|
||||
-DCMAKE_CXX_FLAGS="-march=arch15"
|
||||
time cmake --build build --config Release -j $(nproc)
|
||||
|
||||
ubuntu-26-ppc64le:
|
||||
runs-on: ubuntu-26.04-ppc64le
|
||||
ubuntu-24-ppc64le:
|
||||
runs-on: ubuntu-24.04-ppc64le
|
||||
|
||||
steps:
|
||||
- name: Clone
|
||||
@@ -154,6 +154,12 @@ jobs:
|
||||
libjpeg-dev build-essential libssl-dev \
|
||||
git-lfs
|
||||
|
||||
- name: Toolchain workaround (GCC 14)
|
||||
run: |
|
||||
sudo apt-get install -y gcc-14 g++-14
|
||||
echo "CC=gcc-14" >> "$GITHUB_ENV"
|
||||
echo "CXX=g++-14" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Python Dependencies
|
||||
id: python_depends
|
||||
run: |
|
||||
|
||||
@@ -61,11 +61,6 @@ 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: |
|
||||
|
||||
@@ -40,6 +40,61 @@ env:
|
||||
CTEST_EXCLUDE: "test-llama-archs|test-llama-context|test-fp8-kv"
|
||||
|
||||
jobs:
|
||||
ubuntu-24-openvino:
|
||||
runs-on: [self-hosted, Linux, Intel, OpenVINO]
|
||||
|
||||
env:
|
||||
# Sync versions in build-openvino.yml, ci-self-hosted-openvino.yml, release.yml, release-publish.yml, build-cache.yml, .devops/openvino.Dockerfile, docs/backend/OPENVINO.md
|
||||
OPENVINO_VERSION_MAJOR: "2026.4.1"
|
||||
OPENVINO_VERSION_FULL: "2026.4.1.22982.07f9c262b05"
|
||||
|
||||
steps:
|
||||
- name: Clone
|
||||
id: checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Dependencies
|
||||
id: depends
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential libssl-dev libtbb12 cmake ninja-build python3-pip
|
||||
sudo apt-get install -y ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd
|
||||
|
||||
- name: Setup OpenVINO Toolkit
|
||||
uses: ./.github/actions/linux-setup-openvino
|
||||
with:
|
||||
path: ./openvino_toolkit
|
||||
version_major: ${{ env.OPENVINO_VERSION_MAJOR }}
|
||||
version_full: ${{ env.OPENVINO_VERSION_FULL }}
|
||||
|
||||
- name: Install OpenVINO dependencies
|
||||
run: |
|
||||
cd ./openvino_toolkit
|
||||
chmod +x ./install_dependencies/install_openvino_dependencies.sh
|
||||
echo "Y" | sudo -E ./install_dependencies/install_openvino_dependencies.sh
|
||||
|
||||
- name: Build
|
||||
id: cmake_build
|
||||
run: |
|
||||
source ./openvino_toolkit/setupvars.sh
|
||||
cmake -B build/ReleaseOV -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DGGML_OPENVINO=ON
|
||||
time cmake --build build/ReleaseOV --config Release --parallel
|
||||
|
||||
- name: Test (CPU)
|
||||
id: cmake_test_cpu
|
||||
run: |
|
||||
cd ${{ github.workspace }}
|
||||
ctest --test-dir build/ReleaseOV -L main -E "${{ env.CTEST_EXCLUDE }}" --verbose --timeout 3000
|
||||
|
||||
- name: Test (GPU)
|
||||
id: cmake_test_gpu
|
||||
run: |
|
||||
cd ${{ github.workspace }}
|
||||
export GGML_OPENVINO_DEVICE=GPU
|
||||
ctest --test-dir build/ReleaseOV -L main -E "${{ env.CTEST_EXCLUDE }}" --verbose --timeout 3000
|
||||
|
||||
openvino-windows-2022:
|
||||
runs-on: windows-2022
|
||||
|
||||
|
||||
@@ -213,11 +213,6 @@ 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: |
|
||||
|
||||
@@ -72,7 +72,7 @@ jobs:
|
||||
|
||||
- name: Fetch emdawnwebgpu
|
||||
run: |
|
||||
DAWN_TAG="v20261120.121236"
|
||||
DAWN_TAG="v20260908.214631"
|
||||
EMDAWN_PKG="emdawnwebgpu_pkg-${DAWN_TAG}.zip"
|
||||
echo "Downloading ${EMDAWN_PKG}"
|
||||
curl -L -o emdawn.zip \
|
||||
|
||||
@@ -21,9 +21,7 @@ on:
|
||||
paths: [
|
||||
'.github/workflows/ci-self-hosted-openvino.yml',
|
||||
'ci/run.sh',
|
||||
'CMakeLists.txt',
|
||||
'ggml/CMakeLists.txt',
|
||||
'tests/CMakeLists.txt',
|
||||
'**/CMakeLists.txt',
|
||||
'**/.cmake',
|
||||
'ggml/src/*',
|
||||
'ggml/src/ggml-cpu/**',
|
||||
|
||||
@@ -16,10 +16,6 @@ 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 * * *'
|
||||
@@ -42,14 +38,6 @@ 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
|
||||
@@ -120,9 +108,6 @@ jobs:
|
||||
mv build-matrix.json.tmp build-matrix.json
|
||||
fi
|
||||
|
||||
jq 'map(select(.tag != "musa"))' build-matrix.json > build-matrix.json.tmp
|
||||
mv build-matrix.json.tmp build-matrix.json
|
||||
|
||||
BUILD_MATRIX="$(jq -c . build-matrix.json)"
|
||||
MERGE_MATRIX="$(jq -c '
|
||||
reduce .[] as $entry ({}; .[$entry.tag] |= (
|
||||
@@ -185,7 +170,7 @@ jobs:
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist
|
||||
path: tools/ui/dist
|
||||
|
||||
# - name: Set up QEMU
|
||||
# if: ${{ contains(matrix.config.platforms, 'linux/amd64') }}
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
BODY: ${{ github.event.pull_request.body }}
|
||||
HAS_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'video demo') }}
|
||||
run: |
|
||||
# sections written by demo:pr (see ui/apps/chat/demo/cli.ts): the managed comment
|
||||
# sections written by demo:pr (see tools/ui/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 '<!-- demo:start -->' <<< "$BODY" && grep -qF '<!-- demo:end -->' <<< "$BODY"; } ||
|
||||
|
||||
@@ -130,7 +130,7 @@ jobs:
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist
|
||||
path: tools/ui/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: ui/apps/chat/dist
|
||||
path: tools/ui/dist
|
||||
|
||||
- name: Dependencies
|
||||
id: depends
|
||||
@@ -274,7 +274,7 @@ jobs:
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist
|
||||
path: tools/ui/dist
|
||||
|
||||
- name: Dependencies
|
||||
id: depends
|
||||
@@ -381,7 +381,7 @@ jobs:
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist
|
||||
path: tools/ui/dist
|
||||
|
||||
- name: Dependencies
|
||||
id: depends
|
||||
@@ -479,7 +479,7 @@ jobs:
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist
|
||||
path: tools/ui/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: ui/apps/chat/dist
|
||||
path: tools/ui/dist
|
||||
|
||||
- name: Build
|
||||
id: cmake_build
|
||||
@@ -624,7 +624,7 @@ jobs:
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist
|
||||
path: tools/ui/dist
|
||||
|
||||
- name: Build
|
||||
id: cmake_build
|
||||
@@ -672,7 +672,7 @@ jobs:
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist
|
||||
path: tools/ui/dist
|
||||
|
||||
- name: ccache
|
||||
uses: ggml-org/ccache-action@v1.2.24
|
||||
@@ -894,17 +894,12 @@ jobs:
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist
|
||||
path: tools/ui/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:
|
||||
@@ -1151,11 +1146,6 @@ 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
|
||||
@@ -1470,7 +1460,7 @@ jobs:
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist
|
||||
path: tools/ui/dist
|
||||
|
||||
- name: Dependencies
|
||||
id: depends
|
||||
@@ -1542,7 +1532,7 @@ jobs:
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist
|
||||
path: tools/ui/dist
|
||||
|
||||
- name: Free up disk space
|
||||
uses: ggml-org/free-disk-space@v1.3.1
|
||||
@@ -1657,7 +1647,7 @@ jobs:
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist
|
||||
path: tools/ui/dist
|
||||
|
||||
- name: Dependencies
|
||||
id: depends
|
||||
|
||||
@@ -42,8 +42,6 @@ env:
|
||||
LLAMA_ARG_LOG_PREFIX: 1
|
||||
LLAMA_ARG_LOG_TIMESTAMPS: 1
|
||||
LLAMA_ARG_LOG_VERBOSITY: 10
|
||||
# [TAG_MTMD_NO_REALLOC] must match -DGGML_SCHED_NO_REALLOC=ON below, skips tests that are known to realloc
|
||||
GGML_SCHED_NO_REALLOC: ON
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref || github.run_id }}
|
||||
|
||||
@@ -39,8 +39,6 @@ env:
|
||||
LLAMA_ARG_LOG_PREFIX: 1
|
||||
LLAMA_ARG_LOG_TIMESTAMPS: 1
|
||||
LLAMA_ARG_LOG_VERBOSITY: 10
|
||||
# [TAG_MTMD_NO_REALLOC] must match -DGGML_SCHED_NO_REALLOC=ON below, skips tests that are known to realloc
|
||||
GGML_SCHED_NO_REALLOC: ON
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref || github.run_id }}
|
||||
|
||||
@@ -7,40 +7,6 @@ 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:
|
||||
@@ -90,9 +56,8 @@ jobs:
|
||||
|
||||
- name: Test speculative decoding
|
||||
env:
|
||||
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' }}
|
||||
SPEC_METHODS: compact
|
||||
SPEC_MODEL_DIR: ${{ vars.SPEC_METHOD_MODEL_DIR || format('{0}/spec-models', runner.temp) }}
|
||||
N_GPU_LAYERS: 99
|
||||
run: |
|
||||
cd tools/server/tests
|
||||
|
||||
@@ -175,11 +175,6 @@ 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
|
||||
|
||||
@@ -23,20 +23,20 @@ jobs:
|
||||
with:
|
||||
node-version: "24"
|
||||
# cache: "npm"
|
||||
# cache-dependency-path: "ui/apps/chat/package-lock.json"
|
||||
# cache-dependency-path: "tools/ui/package-lock.json"
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Build application
|
||||
run: npm run build
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Upload built UI
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist/
|
||||
path: tools/ui/dist/
|
||||
retention-days: 1
|
||||
|
||||
@@ -37,26 +37,26 @@ jobs:
|
||||
with:
|
||||
node-version: "24"
|
||||
# cache: "npm"
|
||||
# cache-dependency-path: "ui/apps/chat/package-lock.json"
|
||||
# cache-dependency-path: "tools/ui/package-lock.json"
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Build application
|
||||
env:
|
||||
LLAMA_BUILD_NUMBER: ${{ steps.version.outputs.ui_version }}
|
||||
run: npm run build
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Run PWA unit tests (versioned build output)
|
||||
run: npx vitest --project=unit --run tests/unit/pwa.spec.ts
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Upload built UI
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist/
|
||||
path: tools/ui/dist/
|
||||
retention-days: 1
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
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
|
||||
@@ -1,230 +0,0 @@
|
||||
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.
|
||||
#
|
||||
# The unscoped llama-ui is an alias: once the scoped package is out, the same build is renamed
|
||||
# and published again at the same version, so the two never drift. It is a package of its own
|
||||
# on npm, and needs the same trusted publisher set on it.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
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: Rename the build to the unscoped alias
|
||||
# after the scoped publish, so nothing above sees the changed name. Not on a PR: the
|
||||
# advisory check there is about the version, which the alias shares.
|
||||
if: github.event_name != 'pull_request'
|
||||
run: node scripts/alias-package.mjs
|
||||
working-directory: ${{ env.LIB_DIR }}
|
||||
|
||||
- name: Compare the alias with npm
|
||||
id: alias
|
||||
if: github.event_name != 'pull_request'
|
||||
run: node scripts/npm-version-check.mjs
|
||||
working-directory: ${{ env.LIB_DIR }}
|
||||
|
||||
- name: Publish the alias
|
||||
# its own verdict rather than the scoped one's, so an alias that fell behind catches up
|
||||
# on the next run instead of waiting for a bump
|
||||
if: github.ref == 'refs/heads/master' && steps.alias.outputs.should_publish == 'true' && inputs.dry_run != true
|
||||
env:
|
||||
TAG: ${{ steps.alias.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: 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 }}
|
||||
ALIAS_LATEST: ${{ steps.alias.outputs.latest }}
|
||||
ALIAS_VERDICT: ${{ steps.alias.outputs.verdict || 'not reached' }}
|
||||
ALIAS_NOTE: ${{ steps.alias.outputs.note }}
|
||||
ALIAS_SHOULD: ${{ steps.alias.outputs.should_publish }}
|
||||
EVENT: ${{ github.event_name }}
|
||||
run: |
|
||||
if [ "$DRY" = "true" ]; then published="no (dry run)"
|
||||
elif [ "$SHOULD" = "true" ]; then published=yes
|
||||
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"
|
||||
[ "$EVENT" = "pull_request" ] && exit 0
|
||||
if [ "$DRY" = "true" ]; then published="no (dry run)"
|
||||
elif [ "$ALIAS_SHOULD" = "true" ]; then published=yes
|
||||
else published=no
|
||||
fi
|
||||
{
|
||||
echo
|
||||
echo "### llama-ui (alias) $VERSION"
|
||||
echo
|
||||
echo "| | |"
|
||||
echo "| --- | --- |"
|
||||
echo "| npm latest was | ${ALIAS_LATEST:-nothing published yet} |"
|
||||
echo "| verdict | \`$ALIAS_VERDICT\` |"
|
||||
echo "| published | $published |"
|
||||
echo
|
||||
echo "> $ALIAS_NOTE"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Mind the verdict
|
||||
if: always() && github.event_name != 'pull_request' && steps.version.outcome == 'success'
|
||||
# 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
|
||||
@@ -33,15 +33,15 @@ jobs:
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist/
|
||||
path: tools/ui/dist/
|
||||
run-id: ${{ inputs.run_id }}
|
||||
github-token: ${{ github.token }}
|
||||
|
||||
- name: Create distribution archive
|
||||
run: |
|
||||
tar -czf dist.tar.gz -C ui/apps/chat/dist .
|
||||
tar -czf dist.tar.gz -C tools/ui/dist .
|
||||
sha256sum dist.tar.gz > dist.tar.gz.sha256
|
||||
mv dist.tar.gz dist.tar.gz.sha256 ui/apps/chat/dist/
|
||||
mv dist.tar.gz dist.tar.gz.sha256 tools/ui/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 ui/apps/chat/dist hf://buckets/ggml-org/${{ env.HF_BUCKET_NAME }}/${{ inputs.version_tag }} --delete --quiet
|
||||
hf buckets sync tools/ui/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 ui/apps/chat/dist hf://buckets/ggml-org/${{ env.HF_BUCKET_NAME }}/latest --delete --quiet
|
||||
hf buckets sync tools/ui/dist hf://buckets/ggml-org/${{ env.HF_BUCKET_NAME }}/latest --delete --quiet
|
||||
|
||||
- name: Verify upload
|
||||
run: |
|
||||
|
||||
@@ -17,9 +17,7 @@ on:
|
||||
paths: [
|
||||
'.github/workflows/ui-self-hosted.yml',
|
||||
'.github/workflows/ui-build-self-hosted.yml',
|
||||
'ui/apps/chat/**.*',
|
||||
'ui/lib/ui/**.*',
|
||||
'ui/lib/voice/**.*',
|
||||
'tools/ui/**.*',
|
||||
'tools/server/tests/**.*'
|
||||
]
|
||||
pull_request:
|
||||
@@ -27,9 +25,7 @@ on:
|
||||
paths: [
|
||||
'.github/workflows/ui-self-hosted.yml',
|
||||
'.github/workflows/ui-build-self-hosted.yml',
|
||||
'ui/apps/chat/**.*',
|
||||
'ui/lib/ui/**.*',
|
||||
'ui/lib/voice/**.*',
|
||||
'tools/ui/**.*',
|
||||
'tools/server/tests/**.*'
|
||||
]
|
||||
|
||||
@@ -71,33 +67,33 @@ jobs:
|
||||
- name: Install dependencies
|
||||
id: setup
|
||||
run: npm ci
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Download built UI artifacts
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist/
|
||||
path: tools/ui/dist/
|
||||
|
||||
- name: Run type checking
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npm run check
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Run linting
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npm run lint
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Run Client tests
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npm run test:client
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Run Unit tests
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npm run test:unit
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
e2e-tests:
|
||||
name: E2E Tests
|
||||
@@ -113,25 +109,25 @@ jobs:
|
||||
- name: Install dependencies
|
||||
id: setup
|
||||
run: npm ci
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Download built UI artifacts
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist/
|
||||
path: tools/ui/dist/
|
||||
|
||||
- name: Build Storybook
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npm run build-storybook
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Run UI tests
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npm run test:ui -- --testTimeout=60000
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Run E2E tests
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npm run test:e2e
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
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}"
|
||||
+17
-91
@@ -13,8 +13,7 @@ on:
|
||||
paths: [
|
||||
'.github/workflows/ui.yml',
|
||||
'.github/workflows/ui-build.yml',
|
||||
'ui/apps/chat/**.*',
|
||||
'ui/lib/**.*',
|
||||
'tools/ui/**.*',
|
||||
'tools/server/tests/**.*'
|
||||
]
|
||||
pull_request:
|
||||
@@ -22,8 +21,7 @@ on:
|
||||
paths: [
|
||||
'.github/workflows/ui.yml',
|
||||
'.github/workflows/ui-build.yml',
|
||||
'ui/apps/chat/**.*',
|
||||
'ui/lib/**.*',
|
||||
'tools/ui/**.*',
|
||||
'tools/server/tests/**.*'
|
||||
]
|
||||
|
||||
@@ -68,118 +66,46 @@ jobs:
|
||||
with:
|
||||
node-version: "24"
|
||||
# cache: "npm"
|
||||
# cache-dependency-path: "ui/apps/chat/package-lock.json"
|
||||
# cache-dependency-path: "tools/ui/package-lock.json"
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Download built UI artifacts
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist/
|
||||
path: tools/ui/dist/
|
||||
|
||||
- name: Install dependencies
|
||||
id: setup
|
||||
if: ${{ steps.node.conclusion == 'success' }}
|
||||
run: npm ci
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Run type checking
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npm run check
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Run linting
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npm run lint
|
||||
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
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Install Playwright browsers
|
||||
id: playwright
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npx playwright install --with-deps
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Run Client tests
|
||||
if: ${{ always() && steps.playwright.conclusion == 'success' }}
|
||||
run: npm run test:client
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Run Unit tests (uses pre-built dist/ from ui-build)
|
||||
if: ${{ always() && steps.playwright.conclusion == 'success' }}
|
||||
run: npm run test:unit
|
||||
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
|
||||
|
||||
voice-checks:
|
||||
name: Voice checks
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24"
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
working-directory: ui/lib/voice
|
||||
|
||||
- name: Run type checking
|
||||
run: npm run check
|
||||
working-directory: ui/lib/voice
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
working-directory: ui/lib/voice
|
||||
|
||||
- name: Build the package
|
||||
run: npm run prepack
|
||||
working-directory: ui/lib/voice
|
||||
working-directory: tools/ui
|
||||
|
||||
e2e-tests:
|
||||
name: E2E Tests
|
||||
@@ -198,38 +124,38 @@ jobs:
|
||||
with:
|
||||
node-version: "24"
|
||||
# cache: "npm"
|
||||
# cache-dependency-path: "ui/apps/chat/package-lock.json"
|
||||
# cache-dependency-path: "tools/ui/package-lock.json"
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install dependencies
|
||||
id: setup
|
||||
if: ${{ steps.node.conclusion == 'success' }}
|
||||
run: npm ci
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Download built UI artifacts (reuses ui-build)
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: llama-ui.zip
|
||||
path: ui/apps/chat/dist/
|
||||
path: tools/ui/dist/
|
||||
|
||||
- name: Install Playwright browsers
|
||||
id: playwright
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npx playwright install --with-deps
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Build Storybook
|
||||
if: ${{ always() && steps.playwright.conclusion == 'success' }}
|
||||
run: npm run build-storybook
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Run UI tests
|
||||
if: ${{ always() && steps.playwright.conclusion == 'success' }}
|
||||
run: npm run test:ui -- --testTimeout=60000
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
- name: Run E2E tests (uses pre-built dist/ from ui-build)
|
||||
if: ${{ always() && steps.playwright.conclusion == 'success' }}
|
||||
run: npm run test:e2e
|
||||
working-directory: ui/apps/chat
|
||||
working-directory: tools/ui
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# date: Mon Nov 16 10:05:56 EET 2026
|
||||
# date: Wed Nov 4 12:03:31 EET 2026
|
||||
# this file is auto-generated by scripts/gen-authors.sh
|
||||
|
||||
Нияз Гарифзянов <112617865+garrnizon@users.noreply.github.com>
|
||||
@@ -43,9 +43,7 @@ Aarni Koskela <akx@iki.fi>
|
||||
Aaron Miller <apage43@ninjawhale.com>
|
||||
Aaron Teo <57927438+taronaeo@users.noreply.github.com>
|
||||
Aaron Teo <aaron.teo1@ibm.com>
|
||||
Aaron Thomas <84493696+arxhr007@users.noreply.github.com>
|
||||
Aaryaman Vasishta <aaryaman.vasishta@amd.com>
|
||||
Aayan Karmali <44980366+StockerMC@users.noreply.github.com>
|
||||
Abheek Gulati <abheekg@hotmail.com>
|
||||
abhijain1204fujitsu <139222713+abhijain1204fujitsu@users.noreply.github.com>
|
||||
Abhijit Ramesh <abhijitramesh2k@gmail.com>
|
||||
@@ -114,12 +112,10 @@ Aleksander Grygier <admin@serveurperso.com>
|
||||
Aleksander Grygier <aleksander.grygier@gmail.com>
|
||||
Aleksander Grygier <thichthat@gmail.com>
|
||||
Aleksei Nikiforov <103434461+AlekseiNikiforovIBM@users.noreply.github.com>
|
||||
Alen Požun <kalyx.solutions@proton.me>
|
||||
Alessandro de Oliveira Faria (A.K.A.CABELO) <cabelo@opensuse.org>
|
||||
Alessandro98-git <61804547+Alessandro98-git@users.noreply.github.com>
|
||||
Alex <18387287+wadealexc@users.noreply.github.com>
|
||||
Alex <59368173+AlexGabbia@users.noreply.github.com>
|
||||
Alex <alexzkhr@gmail.com>
|
||||
Alex <awhill19@icloud.com>
|
||||
Alex Azarov <alex@azarov.by>
|
||||
Alex Azarov <alexander.azarov@mapbox.com>
|
||||
@@ -136,7 +132,6 @@ Alex Trotta <44127594+Ahajha@users.noreply.github.com>
|
||||
Alex Tuddenham <61622354+AlexsCode@users.noreply.github.com>
|
||||
Alex von Gluck IV <kallisti5@unixzen.com>
|
||||
Alex Wu <dindinw@users.noreply.github.com>
|
||||
Alex-JP-93 <Jianpeng.Li@amd.com>
|
||||
alex-spacemit <jinghui.huang@spacemit.com>
|
||||
Alexander Batischev <eual.jp@gmail.com>
|
||||
Alexander Heisler <126129661+heislera763@users.noreply.github.com>
|
||||
@@ -148,7 +143,6 @@ Alexis Williams <typedrat@users.noreply.github.com>
|
||||
alexpinel <93524949+alexpinel@users.noreply.github.com>
|
||||
Alfred <zxu3@clemson.edu>
|
||||
Ali Chraghi <63465728+alichraghi@users.noreply.github.com>
|
||||
Ali F. Al-Ramadan <55710790+aalramadan@users.noreply.github.com>
|
||||
Ali Nehzat <ali.nehzat@thanks.dev>
|
||||
Ali Tariq <ali.tariq@10xengineers.ai>
|
||||
Ali Tariq <alitariq4589@gmail.com>
|
||||
@@ -164,7 +158,6 @@ Aman Karki <amankarki151@gmail.com>
|
||||
Aman Karki <itsamankarki@gmail.com>
|
||||
amd-dwang <dong.wang@amd.com>
|
||||
amd-lalithnc <lalithnc@amd.com>
|
||||
AMIR <127450356+amirthn6533@users.noreply.github.com>
|
||||
Amir <amir_zia@outlook.com>
|
||||
amirai21 <89905406+amirai21@users.noreply.github.com>
|
||||
AmirAli Mirian <37371367+amiralimi@users.noreply.github.com>
|
||||
@@ -220,7 +213,6 @@ Antoine Viallon <antoine@lesviallon.fr>
|
||||
Anton I <inflyer@hotmail.com>
|
||||
Anton Mitkov <anton_b_mitkov@abv.bg>
|
||||
Anton Mitkov <anton.mitkov@codeplay.com>
|
||||
Anton Sokolchenko <wsevendays@gmail.com>
|
||||
Antonis Makropoulos <benuix@gmail.com>
|
||||
anubhavfujitsu <Anubhav.Srivastava@fujitsu.com>
|
||||
Anudit Nagar <nagaranudit@gmail.com>
|
||||
@@ -241,12 +233,10 @@ arlo-phoenix <140345165+arlo-phoenix@users.noreply.github.com>
|
||||
Armen Kaleshian <kriation@users.noreply.github.com>
|
||||
Arsen Arutunan <58118221+limloop@users.noreply.github.com>
|
||||
Arseniy Obolenskiy <good.doog.2012@gmail.com>
|
||||
ArshM17-NV <amaknojia@nvidia.com>
|
||||
Artem <guinmoon@gmail.com>
|
||||
Artem Zinnatullin <ceo@abstractny.gay>
|
||||
Artyom Lebedev <vagran.ast@gmail.com>
|
||||
aryantandon01 <80969509+aryantandon01@users.noreply.github.com>
|
||||
Asahi-Prv <246092086+Asahi-Prv@users.noreply.github.com>
|
||||
Asahi-Prv <asahihori7@gmail.com>
|
||||
asbelin <71226900+asbelin@users.noreply.github.com>
|
||||
Asbjørn Olling <asbjornolling@gmail.com>
|
||||
@@ -268,7 +258,6 @@ AustinMroz <austinmroz@utexas.edu>
|
||||
AUTOMATIC1111 <16777216c@gmail.com>
|
||||
automaticcat <daogiatuank54@gmail.com>
|
||||
awatuna <23447591+awatuna@users.noreply.github.com>
|
||||
Awss <gitj.18@alt.awss1i.com>
|
||||
b4b4o <zwbao@foxmail.com>
|
||||
Bach Le <bach@bullno1.com>
|
||||
BADR <contact@pythops.com>
|
||||
@@ -362,7 +351,6 @@ CarterLi999 <664681047@qq.com>
|
||||
Casey Primozic <casey@cprimozic.net>
|
||||
Casey Primozic <me@ameo.link>
|
||||
CausalLM <148736309+CausalLM@users.noreply.github.com>
|
||||
CC <65151926+realMoana@users.noreply.github.com>
|
||||
ccbinn <ccbinn@163.com>
|
||||
cduk <19917266+cduk@users.noreply.github.com>
|
||||
cebtenzzre <cebtenzzre@gmail.com>
|
||||
@@ -391,7 +379,6 @@ Cheng Shao <terrorjack@type.dance>
|
||||
Chenguang Li <757486878@qq.com>
|
||||
Chenguang Li <87689256+noemotiovon@users.noreply.github.com>
|
||||
chiheb ben cheikh <100644963+ChihebBENCHEIKH1@users.noreply.github.com>
|
||||
chinmaykamjith001 <chinmaykamjith@gmail.com>
|
||||
Chipmunk <101038159+CHIPMUNK-T0T@users.noreply.github.com>
|
||||
chiranko <96988916+chiranko@users.noreply.github.com>
|
||||
Chris Danis <cdanis@gmail.com>
|
||||
@@ -447,7 +434,6 @@ crasm <crasm@git.vczf.us>
|
||||
crat0z <11581854+crat0z@users.noreply.github.com>
|
||||
CRD716 <crd716@gmail.com>
|
||||
CrispStrobe <154636388+CrispStrobe@users.noreply.github.com>
|
||||
Cristian Adam <cristian.adam@gmail.com>
|
||||
Cristiano Pinto <140563307+crowmoed@users.noreply.github.com>
|
||||
crsawyer <7572190+crsawyer@users.noreply.github.com>
|
||||
Csaba Kecskemeti <csaba.kecskemeti@gmail.com>
|
||||
@@ -541,7 +527,6 @@ Djip007 <3705339+Djip007@users.noreply.github.com>
|
||||
Djip007 <djip.perois@free.fr>
|
||||
dm4 <dm4@secondstate.io>
|
||||
dm4 <sunrisedm4@gmail.com>
|
||||
Dmitrii Panchev <dmnobunaga@users.noreply.github.com>
|
||||
Dmitry Atamanov <data-man@users.noreply.github.com>
|
||||
Dmytro Minochkin <dmytro.minochkin@gmail.com>
|
||||
Dmytro Romanov <casteldazur@gmail.com>
|
||||
@@ -582,7 +567,6 @@ Ed Addario <29247825+EAddario@users.noreply.github.com>
|
||||
Ed Lee <edilee@mozilla.com>
|
||||
Ed Lepedus <ed.lepedus@googlemail.com>
|
||||
Eddie-Wang <wangjinheng1120@163.com>
|
||||
eddiechen <Echen1246@gmail.com>
|
||||
Eden <aa9736195201@gmail.com>
|
||||
eduardopessin <100053075+eduardopessin@users.noreply.github.com>
|
||||
Edward Taylor <edeetee@gmail.com>
|
||||
@@ -614,7 +598,6 @@ Erik Winter <93544977+ewintr@users.noreply.github.com>
|
||||
Ervin Áron Tasnádi <etasnadi@protonmail.com>
|
||||
Esko Toivonen <eskot98@gmail.com>
|
||||
Ethan Guo <ethanguo.dev@gmail.com>
|
||||
Ethan Lin <linsen458@gmail.com>
|
||||
Ethan Turner <eturner64@gmail.com>
|
||||
Ettore Di Giacinto <mudler@users.noreply.github.com>
|
||||
EugeoSynthesisThirtyTwo <gabriel.dhimoila@gmail.com>
|
||||
@@ -642,7 +625,6 @@ fanyang <fanyang89@outlook.com>
|
||||
Farbod Bijary <110523279+farbodbj@users.noreply.github.com>
|
||||
Fathi Boudra <fathi.boudra@linaro.org>
|
||||
Fattire <528174+fat-tire@users.noreply.github.com>
|
||||
Feiteng <lifeiteng0422@gmail.com>
|
||||
felix <felix314159@users.noreply.github.com>
|
||||
Felix <stenbackfelix@gmail.com>
|
||||
Felix Ye <felixyjs@gmail.com>
|
||||
@@ -650,7 +632,6 @@ fengerhu1 <2748250768@qq.com>
|
||||
feni6 <fenissova@proton.me>
|
||||
fidoriel <49869342+fidoriel@users.noreply.github.com>
|
||||
fiesh <fiesh@zefix.tv>
|
||||
figkcoci-debug <figkcoci@gmail.com>
|
||||
FINAL-Bench <kkms1116@koreacu.ac.kr>
|
||||
Finn Voorhees <finnvoorhees@gmail.com>
|
||||
Firat <firatkiral@gmail.com>
|
||||
@@ -665,7 +646,6 @@ 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 <ppaanncchhoo507@gmail.com>
|
||||
Francisco Melo <43780565+francis2tm@users.noreply.github.com>
|
||||
Francois Dugast <francois.dugast@intel.com>
|
||||
@@ -729,7 +709,6 @@ GiviMAD <GiviMAD@users.noreply.github.com>
|
||||
gliptic <gliptic@users.noreply.github.com>
|
||||
gn64 <yukikaze.jp@gmail.com>
|
||||
goerch <jhr.walter@t-online.de>
|
||||
Gotya-OFFCIAL <zhengfreeman@gmail.com>
|
||||
Govlzkoy <gotope@users.noreply.github.com>
|
||||
grahameth <96447521+grahameth@users.noreply.github.com>
|
||||
Gregor Jasny <gjasny@googlemail.com>
|
||||
@@ -770,7 +749,6 @@ Haowei Wu <breadcyanide@icloud.com>
|
||||
Haoxiang Fei <tonyfettes@tonyfettes.com>
|
||||
Harald Fernengel <harald.fernengel@here.com>
|
||||
Harapan Rachman <harapanrachman@gmail.com>
|
||||
Harkanwal Bedi <bedi1887@gmail.com>
|
||||
Harkirat Gill <harkirat.gill@amd.com>
|
||||
HarrisonSec <gzxharrison@gmail.com>
|
||||
Hatsune Miku <129688334+at8u@users.noreply.github.com>
|
||||
@@ -790,7 +768,6 @@ Henrik Forstén <henrik.forsten@gmail.com>
|
||||
Henry Linjamäki <henry.linjamaki@gmail.com>
|
||||
Henry Linjamäki <henry.mikael.linjamaki@intel.com>
|
||||
Henry147147 <44851451+Henry147147@users.noreply.github.com>
|
||||
Hera <58063257+hera2019@users.noreply.github.com>
|
||||
Herman Semenoff <GermanAizek@yandex.ru>
|
||||
Herman Semenov <GermanAizek@yandex.ru>
|
||||
Hesen Peng <hesen.peng@gmail.com>
|
||||
@@ -869,7 +846,6 @@ Imad Saddik <79410781+ImadSaddik@users.noreply.github.com>
|
||||
iMil <imil@NetBSD.org>
|
||||
Incarnas <119618389+bit-incarnas@users.noreply.github.com>
|
||||
InflexCZE <martin.pavlicek11@gmail.com>
|
||||
Iñigo Imaz <49730431+inimaz@users.noreply.github.com>
|
||||
Intel AI Get-to Market Customer Success and Solutions <ai.gtm.css@gmail.com>
|
||||
intelmatt <61025942+intelmatt@users.noreply.github.com>
|
||||
iohub <rickyang.pro@gmail.com>
|
||||
@@ -881,9 +857,7 @@ IsaacDynamo <61521674+IsaacDynamo@users.noreply.github.com>
|
||||
Ishaan Gandhi <Ishaangandhi@gmail.com>
|
||||
iSma <ismail.senhaji@gmail.com>
|
||||
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 <nekotekina@gmail.com>
|
||||
@@ -914,7 +888,6 @@ James Francis <6763899+JamesFranc@users.noreply.github.com>
|
||||
James O'Leary <65884233+jpohhhh@users.noreply.github.com>
|
||||
James Reynolds <magnusviri@users.noreply.github.com>
|
||||
jameswu2014 <545426914@qq.com>
|
||||
JamieBordoni <jamie.bordoni@protonmail.com>
|
||||
Jan Boon <jan.boon@kaetemi.be>
|
||||
Jan Boon <kaetemi@gmail.com>
|
||||
Jan Ekström <jeebjp@gmail.com>
|
||||
@@ -983,10 +956,8 @@ Jinyang He <hejinyang@loongson.cn>
|
||||
jinzihao <jinzihao1996@gmail.com>
|
||||
Jiří Podivín <66251151+jpodivin@users.noreply.github.com>
|
||||
Jiří Sejkora <Sejseloid@gmail.com>
|
||||
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 <jjperry69@gmail.com>
|
||||
jklincn <985765408@qq.com>
|
||||
jklincn <jklincn@outlook.com>
|
||||
JM Robles <roblesjm@gmail.com>
|
||||
@@ -999,7 +970,6 @@ Joe Rowell <joerowell4@gmail.com>
|
||||
Joe Todd <joe.todd@codeplay.com>
|
||||
joecryptotoo <80373433+joecryptotoo@users.noreply.github.com>
|
||||
Joel <agnel.joel@gmail.com>
|
||||
Joel Fernandes <joelagnelf@nvidia.com>
|
||||
Johan <JohanAR@users.noreply.github.com>
|
||||
Johannes Gäßler <johannesg@5d6.de>
|
||||
Johannes Rudolph <johannes.rudolph@gmail.com>
|
||||
@@ -1018,7 +988,6 @@ 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.j.buck@gmail.com>
|
||||
Jonathan Clohessy <jonathan.clohessy@arm.com>
|
||||
Jonathan Graehl <99024+graehl@users.noreply.github.com>
|
||||
Jorge A <161275481+jorgealias@users.noreply.github.com>
|
||||
@@ -1128,7 +1097,6 @@ klosax <131523366+klosax@users.noreply.github.com>
|
||||
KnightYao <KnightYao@users.noreply.github.com>
|
||||
KokerZhou <111279477+KokerZhou@users.noreply.github.com>
|
||||
Kolen Cheung <ickc@users.noreply.github.com>
|
||||
Kong Jiale <2049447146@qq.com>
|
||||
kononnable <kononnable@gmail.com>
|
||||
Konrad Moren <kmoren@nvidia.com>
|
||||
konradmb <konradmb@o2.pl>
|
||||
@@ -1199,7 +1167,6 @@ li-lizhe <82501526+li-lizhe@users.noreply.github.com>
|
||||
liangliangchang <lichang@amd.com>
|
||||
liminfei-amd <91481003+liminfei-amd@users.noreply.github.com>
|
||||
limitedAtonement <limitedAtonement@users.noreply.github.com>
|
||||
Lines <linellazatin@gmail.com>
|
||||
lingyezhixing <144504450+lingyezhixing@users.noreply.github.com>
|
||||
linsen458-spec <linsen458@gmail.com>
|
||||
Linux User <linuxusergd@outlook.com>
|
||||
@@ -1260,7 +1227,6 @@ makomk <makosoft@googlemail.com>
|
||||
manayang <jackmanayang@gmail.com>
|
||||
manikbhandari <mbbhandarimanik2@gmail.com>
|
||||
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 <subscriptions@marckohlbrugge.com>
|
||||
@@ -1370,7 +1336,6 @@ Michael Hueschen <m@mhueschen.dev>
|
||||
Michael Kesper <mkesper@schokokeks.org>
|
||||
Michael Klimenko <mklimenko29@gmail.com>
|
||||
Michael Lamothe <michael.lamothe@gmail.com>
|
||||
Michael Paulauski <mike10010100@gmail.com>
|
||||
Michael Podvitskiy <podvitskiymichael@gmail.com>
|
||||
Michael Potter <NanoTekGuy@Gmail.com>
|
||||
Michael Taylor <162068037+mctylr-gh@users.noreply.github.com>
|
||||
@@ -1490,7 +1455,6 @@ Nikolay Popov <131475237+npopov-vst@users.noreply.github.com>
|
||||
Nils Gladitz <nilsgladitz@gmail.com>
|
||||
Nindaleth <Nindaleth@users.noreply.github.com>
|
||||
ningshanwutuobang <ningshanwutuobang@gmail.com>
|
||||
Nisbenz <benazzaanis783@gmail.com>
|
||||
Noah <99681487+NoahOksuz@users.noreply.github.com>
|
||||
nold <Nold360@users.noreply.github.com>
|
||||
nopperl <54780682+nopperl@users.noreply.github.com>
|
||||
@@ -1498,7 +1462,6 @@ nullname <chraac@gmail.com>
|
||||
Nuno <rare-magma@posteo.eu>
|
||||
nuri <yoonuri1@gmail.com>
|
||||
nusu-github <29514220+nusu-github@users.noreply.github.com>
|
||||
nv-vankit <162085734+nv-vankit@users.noreply.github.com>
|
||||
nwyin <tommynguyen0512@gmail.com>
|
||||
o7si <32285332+o7si@users.noreply.github.com>
|
||||
Oğuzhan Akkaya <oakkaya@ymail.com>
|
||||
@@ -1522,7 +1485,6 @@ oobabooga <oobabooga4@gmail.com>
|
||||
opparco <parco.opaai@gmail.com>
|
||||
Ori Pekelman <ori@pekelman.com>
|
||||
Oscar Barenys <rtfss1@gmail.com>
|
||||
Oscar M. Herrera <oscar@kss-inc.com>
|
||||
OSecret <135510162+OLSecret@users.noreply.github.com>
|
||||
ostix360 <55257054+ostix360@users.noreply.github.com>
|
||||
Ouadie EL FAROUKI <ouadie.elfarouki@codeplay.com>
|
||||
@@ -1649,7 +1611,6 @@ Raj Hammeer Singh Hada <hammeerraj@gmail.com>
|
||||
Rajendra Matcha <matcraje@qti.qualcomm.com>
|
||||
Ralph Soika <ralph.soika@imixs.com>
|
||||
Raman Shinde <raman.shinde15@gmail.com>
|
||||
Ramzi <146260554+rmz-24@users.noreply.github.com>
|
||||
Rand Xie <randxiexyy29@gmail.com>
|
||||
Randall Fitzgerald <randall@dasaku.net>
|
||||
Random Fly <renfei8@live.cn>
|
||||
@@ -1690,7 +1651,6 @@ Rich Dougherty <rich@rd.nz>
|
||||
Richard <r-burton@hotmail.co.uk>
|
||||
Richard Davison <richard.davison1@gmail.com>
|
||||
Richard Kiss <him@richardkiss.com>
|
||||
Richard Palethorpe <io@richiejp.com>
|
||||
Richard Roberson <richardr1126@gmail.com>
|
||||
RichardScottOZ <rnmscott@netspace.net.au>
|
||||
Rick G <26732651+TheFlipbook@users.noreply.github.com>
|
||||
@@ -1735,7 +1695,6 @@ Roni <sulpher@gmx.net>
|
||||
Ronny Brendel <ronnyb@nvidia.com>
|
||||
Ronny Brendel <ronnybrendel@gmail.com>
|
||||
Ronsor <ronsor@ronsor.pw>
|
||||
Roshan Kumar <52444089+roshankumarg529@users.noreply.github.com>
|
||||
Rotem Dan <rotemdan@gmail.com>
|
||||
Rowan Hart <rowanbhart@gmail.com>
|
||||
rspOverflow <217881046+rspOverflow@users.noreply.github.com>
|
||||
@@ -1768,11 +1727,9 @@ Saba Fallah <10401143+sfallah@users.noreply.github.com>
|
||||
Saba Fallah <sabafallah@gmail.com>
|
||||
Sachin Desai <smdesai@gmail.com>
|
||||
Sachin Sharma <sachin@zettabolt.com>
|
||||
Saejin Kim-Heinert <saejinmh@gmail.com>
|
||||
Safi Ullah <safiullah.3915@gmail.com>
|
||||
safranowith <bsh155762@gmail.com>
|
||||
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 <yukinon244@gmail.com>
|
||||
Salvador E. Tropea <stropea@inti.gob.ar>
|
||||
@@ -1797,7 +1754,6 @@ Sang-Kil Park <sang.park@42dot.ai>
|
||||
Sanjay Ahari <sanjayahari1704@gmail.com>
|
||||
Sarah Wu <sarahwu185@gmail.com>
|
||||
Sarah Wu <sarwu@nvidia.com>
|
||||
sargentmajord <jasonlather13@gmail.com>
|
||||
Sascha Rogmann <59577610+srogmann@users.noreply.github.com>
|
||||
sasha0552 <admin@sasha0552.org>
|
||||
Satinder Grewal <grewal.satinder@gmail.com>
|
||||
@@ -1830,7 +1786,6 @@ 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 <seryogakovalyov@gmail.com>
|
||||
Seungjun Bae <linkedlatch@gmail.com>
|
||||
Seungmin Kim <8457324+ehfd@users.noreply.github.com>
|
||||
SeungWon Jeong <65549245+redlion0929@users.noreply.github.com>
|
||||
Seyoung Jeong <seyoungjeong@gmail.com>
|
||||
@@ -1916,7 +1871,6 @@ SmartestWashingMachine <ottobizness@gmail.com>
|
||||
smugman-dot <wbsmoke101@gmail.com>
|
||||
SnA1lGo <44647694+skrandy@users.noreply.github.com>
|
||||
snadampal <87143774+snadampal@users.noreply.github.com>
|
||||
Sofian Elmotiem <sofianelmotiem@gmail.com>
|
||||
SoftwareRenderer <138734813+SoftwareRenderer@users.noreply.github.com>
|
||||
Someone <sergei.kozlukov@aalto.fi>
|
||||
Someone Serge <sergei.kozlukov@aalto.fi>
|
||||
@@ -1932,7 +1886,6 @@ sprayandwipe <spray.and.wipe@gmail.com>
|
||||
Sreeram <sreeram.sivasubramony@amd.com>
|
||||
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 <nivibilla@gmail.com>
|
||||
srkizer <github.soreepeong.prqovzj1d@srkizer.net>
|
||||
ssweens <1149151+ssweens@users.noreply.github.com>
|
||||
@@ -1966,7 +1919,6 @@ Sutou Kouhei <kou@cozmixng.org>
|
||||
Svetlozar Georgiev <55534064+sgeor255@users.noreply.github.com>
|
||||
Swigler <124839156+Swigler@users.noreply.github.com>
|
||||
swittk <switt1995@gmail.com>
|
||||
sxq <18856096915@163.com>
|
||||
SXX <song_xiaoxi@126.com>
|
||||
SXX <sxx1136965276@gmail.com>
|
||||
Tai Duc Nguyen <taiducnguyen.drexel@gmail.com>
|
||||
@@ -2092,7 +2044,6 @@ Ulrich Drepper <drepper@gmail.com>
|
||||
unbounded <haakon@likedan.net>
|
||||
Unbug Lee <tidelgl@gmail.com>
|
||||
unraido <127105806+unraido@users.noreply.github.com>
|
||||
usrlocalben <benjamin@rqdq.com>
|
||||
uvos <carl@uvos.xyz>
|
||||
uvos <devnull@uvos.xyz>
|
||||
uvos <philipp@uvos.xyz>
|
||||
@@ -2133,7 +2084,6 @@ vk <89937361+itsvedantkumar@users.noreply.github.com>
|
||||
Vlad <spitfireage@gmail.com>
|
||||
Vladimir <bogdad@gmail.com>
|
||||
Vladimir Malyutin <first-leon@yandex.ru>
|
||||
Vladimir Sotnikov <bubert9@gmail.com>
|
||||
Vladimir Vuksanovic <109677816+vvuksanovic@users.noreply.github.com>
|
||||
Vladimir Zorin <vladimir@deviant.guru>
|
||||
Vladislav <vladplotnikov34@gmail.com>
|
||||
@@ -2189,7 +2139,6 @@ Wroclaw <wroclaw223@outlook.com>
|
||||
wsbagnsv1 <sclumpfpapa36@gmail.com>
|
||||
Wu Jian Ping <wujjpp@hotmail.com>
|
||||
Wu Jian Ping <wujp@greatld.com>
|
||||
WuXin <apuravmanhas123@gmail.com>
|
||||
wwoodsTM <104587230+wwoodsTM@users.noreply.github.com>
|
||||
Wyatt Caldwell <218154709+Detensable@users.noreply.github.com>
|
||||
wzy <32936898+Freed-Wu@users.noreply.github.com>
|
||||
@@ -2213,7 +2162,6 @@ 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 <son@huggingface.co>
|
||||
Xuan Son Nguyen <thichthat@gmail.com>
|
||||
Xuan-Son Nguyen <son@huggingface.co>
|
||||
Xuan-Son Nguyen <thichthat@gmail.com>
|
||||
@@ -2299,7 +2247,6 @@ zhangrunda <zhangrunda1234@outlook.com>
|
||||
zhangtao2-1 <478679312@qq.com>
|
||||
ZHAOKAI WANG <sanxianwei@163.com>
|
||||
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 <zhentao.yu@intel.com>
|
||||
Zhenwei Jin <109658203+kylo5aby@users.noreply.github.com>
|
||||
|
||||
+1
-1
@@ -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 Llama Chat, the embedded chat app, for server" OFF)
|
||||
option(LLAMA_BUILD_UI "llama: build the embedded Web UI 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)
|
||||
|
||||
|
||||
+1
-1
@@ -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
|
||||
/ui/ @ggml-org/llama-ui
|
||||
/tools/ui/ @ggml-org/llama-ui
|
||||
/tools/tokenize/ @ggerganov
|
||||
/tools/tts/ @ggerganov
|
||||
/vendor/ @ggerganov
|
||||
|
||||
@@ -16,8 +16,6 @@ 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.
|
||||
@@ -26,16 +24,6 @@ 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)
|
||||
|
||||
@@ -7,22 +7,16 @@
|
||||
<b>LLM inference in C/C++</b>
|
||||
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://github.com/ggml-org/llama.cpp/releases?q=tag:v1)
|
||||
[](https://github.com/ggml-org/llama.cpp/releases?q=tag:v1)
|
||||
[](https://github.com/ggml-org/llama.cpp/releases?q=b)
|
||||
[](https://github.com/ggml-org/llama.cpp/actions/workflows/server.yml)
|
||||
[](https://github.com/ggml-org/llama.cpp/actions/workflows/docker.yml)
|
||||
[](https://github.com/ggml-org/llama.cpp/actions/workflows/winget.yml)
|
||||
|
||||
[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)
|
||||
[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)
|
||||
|
||||
</div>
|
||||
|
||||
## 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:
|
||||
@@ -57,12 +51,50 @@ llama serve -hf ggml-org/Qwen3.5-0.8B-GGUF
|
||||
<i>VLM session with <b>llama cli</b></i>
|
||||
</td>
|
||||
<td align="center">
|
||||
<img width="1392" height="958" alt="Llama Chat, the built-in chat app, against `llama serve` running Qwen 3.6" src="https://github.com/user-attachments/assets/b402f972-2e32-4def-8771-8d849f08cf2e" />
|
||||
<i>Llama Chat, the built-in chat app, against <b>llama serve</b></i>
|
||||
<img width="1392" height="958" alt="Built-in web UI against `llama serve` running Qwen 3.6" src="https://github.com/user-attachments/assets/b402f972-2e32-4def-8771-8d849f08cf2e" />
|
||||
<i>Built-in web UI against <b>llama serve</b></i>
|
||||
</td>
|
||||
</tr>
|
||||
<table>
|
||||
|
||||
## 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
|
||||
@@ -70,7 +102,6 @@ llama serve -hf ggml-org/Qwen3.5-0.8B-GGUF
|
||||
- [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
|
||||
|
||||
+1
-1
@@ -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:
|
||||
- Llama Chat, the built-in chat app (`ui/apps/chat`)
|
||||
- Web UI
|
||||
- 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
|
||||
|
||||
@@ -122,8 +122,6 @@ 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
|
||||
|
||||
|
||||
+12
-40
@@ -326,7 +326,7 @@ static bool parse_bool_value(const std::string & value) {
|
||||
// common_models_handler
|
||||
//
|
||||
|
||||
std::string common_get_default_local_path(const std::string & url) {
|
||||
static std::string get_default_local_path(const std::string & url) {
|
||||
auto f = string_split<std::string>(url, '#').front();
|
||||
f = string_split<std::string>(f, '?').front();
|
||||
return fs_get_cache_file(string_split<std::string>(f, '/').back()).string();
|
||||
@@ -349,14 +349,6 @@ 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();
|
||||
@@ -381,7 +373,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 || spec_type_draft_dflash2 || spec_type_draft_lilicorr;
|
||||
opts.download_dflash = spec_type_draft_dflash;
|
||||
opts.download_dspark = spec_type_draft_dspark;
|
||||
opts.download_mmproj = use_mmproj && !params.no_mmproj
|
||||
&& params.mmproj.path.empty() && params.mmproj.url.empty();
|
||||
@@ -436,7 +428,7 @@ static std::vector<common_download_task> build_url_tasks(const common_params_mod
|
||||
if (parts.size() == 1) {
|
||||
common_download_task task;
|
||||
task.url = parts[0];
|
||||
task.local_path = model.path.empty() ? common_get_default_local_path(parts[0]) : model.path;
|
||||
task.local_path = model.path.empty() ? get_default_local_path(parts[0]) : model.path;
|
||||
task.opts = opts;
|
||||
tasks.push_back(std::move(task));
|
||||
return tasks;
|
||||
@@ -454,7 +446,7 @@ static std::vector<common_download_task> build_url_tasks(const common_params_mod
|
||||
task.url = part;
|
||||
task.opts = opts;
|
||||
|
||||
std::string local = common_get_default_local_path(part);
|
||||
std::string local = get_default_local_path(part);
|
||||
if (!base_dir.empty()) {
|
||||
auto pos = local.rfind('/');
|
||||
std::string name = pos == std::string::npos ? local : local.substr(pos + 1);
|
||||
@@ -487,7 +479,7 @@ void common_models_handler_apply(common_models_handler & handler, common_params
|
||||
auto handle_url = [&](common_params_model & model) {
|
||||
if (!model.url.empty()) {
|
||||
if (model.path.empty()) {
|
||||
model.path = common_get_default_local_path(model.url);
|
||||
model.path = get_default_local_path(model.url);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -498,7 +490,7 @@ void common_models_handler_apply(common_models_handler & handler, common_params
|
||||
// optionally, if docker repo is set, resolve it
|
||||
if (!params.model.docker_repo.empty()) {
|
||||
params.model.url = common_docker_resolve_model(params.model.docker_repo);
|
||||
params.model.path = common_get_default_local_path(params.model.url);
|
||||
params.model.path = get_default_local_path(params.model.url);
|
||||
}
|
||||
|
||||
// handle plain "url" tasks (non-hf)
|
||||
@@ -912,10 +904,6 @@ 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 ||
|
||||
@@ -2833,7 +2821,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<std::string> 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())
|
||||
);
|
||||
@@ -2899,7 +2887,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<std::string> 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())
|
||||
);
|
||||
@@ -3420,20 +3408,12 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
|
||||
add_opt(common_arg(
|
||||
{"--ui-mcp-proxy", "--webui-mcp-proxy"},
|
||||
{"--no-ui-mcp-proxy", "--no-webui-mcp-proxy"},
|
||||
"experimental: whether to enable MCP CORS proxy, for Llama Chat to reach public MCP servers without CORS headers; local and private addresses are refused unless --ui-mcp-proxy-allow-private-urls is set - do not enable in untrusted environments (default: disabled)\n"
|
||||
"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"
|
||||
"note: for security reasons, this will limit --cors-origins to localhost by default",
|
||||
[](common_params & params, bool value) {
|
||||
params.ui_mcp_proxy = value;
|
||||
}
|
||||
).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_MCP_PROXY"));
|
||||
add_opt(common_arg(
|
||||
{"--ui-mcp-proxy-allow-private-urls"},
|
||||
"allow the MCP CORS proxy to reach local or private addresses (e.g. MCP servers on localhost or LAN) - anyone who can reach the proxy can then reach your local network (default: disabled, only public addresses)\n"
|
||||
"note: only has effect with --ui-mcp-proxy",
|
||||
[](common_params & params) {
|
||||
params.ui_mcp_proxy_allow_private_urls = true;
|
||||
}
|
||||
).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_MCP_PROXY_ALLOW_PRIVATE_URLS"));
|
||||
add_opt(common_arg(
|
||||
{"--tools"}, "TOOL1,TOOL2,...",
|
||||
"experimental: whether to enable built-in tools for AI agents - do not enable in untrusted environments (default: no tools)\n"
|
||||
@@ -3497,7 +3477,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 Llama Chat, the built-in chat app (default: %s)", params.ui ? "enabled" : "disabled"),
|
||||
string_format("whether to enable the Web UI (default: %s)", params.ui ? "enabled" : "disabled"),
|
||||
[](common_params & params, bool value) {
|
||||
params.ui = value;
|
||||
}
|
||||
@@ -4514,7 +4494,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 docs/multimodal/tts.md for per-model usage notes",
|
||||
"see tts/README.md for per-model usage notes",
|
||||
[](common_params & params, const std::string & value) {
|
||||
params.tts_lang = value;
|
||||
}
|
||||
@@ -4522,7 +4502,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 docs/multimodal/tts.md for per-model usage notes",
|
||||
"see tts/README.md for per-model usage notes",
|
||||
[](common_params & params, const std::string & value) {
|
||||
params.tts_voice = value;
|
||||
}
|
||||
@@ -4534,14 +4514,6 @@ 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
|
||||
|
||||
@@ -149,9 +149,6 @@ common_models_handler common_models_handler_init(const common_params & params, l
|
||||
// check if the model is a preset repo (i.e. has a preset file)
|
||||
bool common_models_handler_is_preset_repo(const common_models_handler & handler);
|
||||
|
||||
// the cache path a model downloaded from a plain url is stored at
|
||||
std::string common_get_default_local_path(const std::string & url);
|
||||
|
||||
// download and update params with the downloaded model path
|
||||
void common_models_handler_apply(common_models_handler & handler, common_params & params, common_download_callback * callback = nullptr);
|
||||
|
||||
|
||||
@@ -69,21 +69,9 @@ common_chat_params peg_generator::generate_parser(const common_chat_template &
|
||||
std::string trigger_marker = !autoparser.tools.format.section_start.empty() ? autoparser.tools.format.section_start :
|
||||
autoparser.tools.format.per_call_start;
|
||||
|
||||
// bare JSON calls without a start marker (e.g. Llama 3.x): trigger the lazy grammar on the call's opening instead
|
||||
std::string trigger_pattern;
|
||||
{
|
||||
const auto & fmt = autoparser.tools.format;
|
||||
bool top_level_name = (fmt.function_field.empty() || fmt.function_field == "function") &&
|
||||
fmt.name_field.find('.') == std::string::npos;
|
||||
if (trigger_marker.empty() && fmt.mode == tool_format::JSON_NATIVE && !fmt.fun_name_is_key &&
|
||||
!fmt.tools_array_wrapped && top_level_name) {
|
||||
trigger_pattern = "\\{\\s*\"" + regex_escape(fmt.name_field) + "\"\\s*:";
|
||||
}
|
||||
}
|
||||
|
||||
bool has_response_format = !inputs.json_schema.empty() && inputs.json_schema.is_object();
|
||||
bool include_grammar = has_response_format || (has_tools &&
|
||||
((inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO && (!trigger_marker.empty() || !trigger_pattern.empty())) ||
|
||||
((inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO && !trigger_marker.empty()) ||
|
||||
inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED));
|
||||
|
||||
if (include_grammar) {
|
||||
@@ -94,11 +82,9 @@ common_chat_params peg_generator::generate_parser(const common_chat_template &
|
||||
|
||||
// Set grammar triggers based on tool section markers (fall back to per-call markers)
|
||||
if (data.grammar_lazy) {
|
||||
if (!trigger_marker.empty()) {
|
||||
data.grammar_triggers = { { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, trigger_marker } };
|
||||
} else {
|
||||
data.grammar_triggers = { { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, trigger_pattern } };
|
||||
}
|
||||
data.grammar_triggers = {
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, trigger_marker }
|
||||
};
|
||||
if (autoparser.tools.format.openai_wrapper_trigger) {
|
||||
// model emits the OpenAI function wrapper, trigger on it
|
||||
data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "{\"type\": \"function\"," });
|
||||
@@ -373,9 +359,7 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
|
||||
auto & p = ctx.p;
|
||||
const auto & inputs = ctx.inputs;
|
||||
|
||||
// A raw string value needs a suffix to end on, without one it is parsed as JSON
|
||||
bool raw_strings = !arguments.value_suffix.empty();
|
||||
auto until_suffix = raw_strings ? p.rule("until-suffix", p.until(arguments.value_suffix)) : p.eps();
|
||||
auto until_suffix = p.rule("until-suffix", p.until(arguments.value_suffix));
|
||||
|
||||
common_peg_parser tool_choice = p.choice();
|
||||
|
||||
@@ -391,9 +375,9 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
|
||||
p.tool_arg(p.tool_arg_open(arguments.name_prefix + p.tool_arg_name(p.literal(param.name)) +
|
||||
arguments.name_suffix) +
|
||||
arguments.value_prefix +
|
||||
(raw_strings && param.schema->may_be_string() ?
|
||||
p.through(p.tool_arg_string_value(until_suffix),
|
||||
p.tool_arg_close(p.literal(arguments.value_suffix))) :
|
||||
(param.schema->may_be_string() ?
|
||||
p.ac(p.tool_arg_string_value(until_suffix) +
|
||||
p.tool_arg_close(p.literal(arguments.value_suffix)), arguments.value_suffix) :
|
||||
(p.tool_arg_json_value(p.schema(
|
||||
p.json(), "tool-" + std::to_string(tool_index) + "-arg-" + std::to_string(param_index) + "-schema", doc, *param.schema)) +
|
||||
p.tool_arg_close(p.literal(arguments.value_suffix)))));
|
||||
|
||||
@@ -71,7 +71,6 @@ struct generation_params {
|
||||
bool is_inference = true;
|
||||
bool add_inference = false;
|
||||
bool mark_input = true; // whether to mark input strings in the jinja context
|
||||
common_peg_tokens specials;
|
||||
|
||||
bool has_continuation() const {
|
||||
return continue_final_message != COMMON_CHAT_CONTINUATION_NONE && !continue_msg.empty();
|
||||
|
||||
@@ -562,8 +562,7 @@ 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_undeclared) {
|
||||
bool allow_json_literals) {
|
||||
if (!tools.is_array() || tools.empty()) {
|
||||
return eps();
|
||||
}
|
||||
@@ -621,18 +620,6 @@ 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() + "]";
|
||||
}
|
||||
|
||||
@@ -71,9 +71,6 @@ constexpr size_t COMMON_CHAT_MAX_PERMUTE = 6;
|
||||
|
||||
class common_chat_peg_builder : public common_peg_parser_builder {
|
||||
public:
|
||||
common_chat_peg_builder() = default;
|
||||
explicit common_chat_peg_builder(common_peg_tokens tokens) : common_peg_parser_builder(std::move(tokens)) {}
|
||||
|
||||
// Tag constants (from former common_chat_peg_base_builder)
|
||||
static constexpr const char * REASONING_BLOCK = "reasoning-block";
|
||||
static constexpr const char * REASONING = "reasoning";
|
||||
@@ -164,11 +161,9 @@ 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_undeclared = false);
|
||||
bool allow_json_literals);
|
||||
|
||||
private:
|
||||
// Python values plus JSON true/false/null.
|
||||
@@ -203,14 +198,6 @@ inline common_peg_arena build_chat_peg_parser(
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
inline common_peg_arena build_chat_peg_parser(
|
||||
const common_peg_tokens & specials,
|
||||
const std::function<common_peg_parser(common_chat_peg_builder & builder)> & fn) {
|
||||
common_chat_peg_builder builder(specials);
|
||||
builder.set_root(fn(builder));
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
class tag_based_peg_mapper {
|
||||
public:
|
||||
std::map<std::string, std::string> tags;
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
#include "jinja/runtime.h"
|
||||
#include "jinja/value.h"
|
||||
#include "json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
@@ -858,45 +857,8 @@ static value tts_norm_builtin_sub(const func_args & args) {
|
||||
return mk_val<value_string>(string(res, text_val.all_parts_are_input()));
|
||||
}
|
||||
|
||||
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<const common_tts_dicts> dicts, common_tts_g2p g2p) {
|
||||
void common_chat_tts_norm_add_builtins(context & ctx) {
|
||||
ctx.set_val("tts_norm_scan", mk_val<value_func>("tts_norm_scan", tts_norm_builtin_scan));
|
||||
ctx.set_val("tts_norm_sub", mk_val<value_func>("tts_norm_sub", tts_norm_builtin_sub));
|
||||
ctx.set_val("tts_dict", mk_val<value_func>("tts_dict", [dicts](const func_args & args) -> value {
|
||||
args.ensure_count(2, 2);
|
||||
args.ensure_vals<value_string, value_string>();
|
||||
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<value_none>();
|
||||
}
|
||||
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<value_func>("tts_g2p", [g2p](const func_args & args) -> value {
|
||||
args.ensure_count(1, 1);
|
||||
args.ensure_vals<value_string>();
|
||||
const std::string out = g2p ? g2p(args.get_pos(0)->as_string().str()) : std::string();
|
||||
if (out.empty()) {
|
||||
return mk_val<value_none>();
|
||||
}
|
||||
return mk_val<value_string>(out);
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
+3
-22
@@ -1,8 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
@@ -13,10 +11,9 @@
|
||||
// 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
|
||||
//
|
||||
// functions exposed to task templates (e.g. "tts") via common_chat_tts_norm_add_builtins():
|
||||
// two functions are 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;
|
||||
@@ -60,22 +57,6 @@ std::vector<common_tts_norm_segment> 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);
|
||||
|
||||
// a dictionary of the model, e.g. a pronunciation lexicon
|
||||
struct common_tts_dict {
|
||||
std::vector<std::string> keys; // sorted by their bytes
|
||||
std::vector<std::string> values; // the JSON document of each key
|
||||
};
|
||||
|
||||
using common_tts_dicts = std::map<std::string, common_tts_dict>;
|
||||
|
||||
// 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<std::string(const std::string & word)>;
|
||||
|
||||
// add tts_norm_scan(), tts_norm_sub(), tts_dict() and tts_g2p() to the context of a task template
|
||||
// add tts_norm_scan() and tts_norm_sub() 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, std::shared_ptr<const common_tts_dicts> dicts = nullptr,
|
||||
common_tts_g2p g2p = nullptr);
|
||||
void common_chat_tts_norm_add_builtins(jinja::context & ctx);
|
||||
|
||||
+20
-69
@@ -315,11 +315,9 @@ struct common_chat_templates {
|
||||
bool add_bos;
|
||||
bool add_eos;
|
||||
bool has_explicit_template; // Model had builtin template or template overridden was specified.
|
||||
common_peg_tokens specials;
|
||||
std::unique_ptr<common_chat_template> template_default; // always set (defaults to chatml)
|
||||
std::unique_ptr<common_chat_template> template_tool_use;
|
||||
std::unique_ptr<common_chat_template> template_tts; // the prompt of a text to speak
|
||||
std::shared_ptr<common_tts_dicts> 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) {
|
||||
@@ -803,20 +801,15 @@ void common_chat_templates_free(struct common_chat_templates * tmpls) {
|
||||
delete tmpls;
|
||||
}
|
||||
|
||||
void common_chat_templates_set_specials(struct common_chat_templates * tmpls, common_peg_tokens specials) {
|
||||
tmpls->specials = std::move(specials);
|
||||
}
|
||||
|
||||
bool common_chat_templates_was_explicit(const struct common_chat_templates * tmpls) {
|
||||
return tmpls->has_explicit_template;
|
||||
}
|
||||
|
||||
// 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, const std::shared_ptr<common_tts_dicts> & tts_dicts,
|
||||
const common_tts_g2p & g2p = nullptr) {
|
||||
static std::string common_chat_template_render(const common_chat_template & tmpl, const json & vars) {
|
||||
jinja::context ctx(tmpl.source());
|
||||
// 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);
|
||||
// text normalization helpers: tts_norm_scan() and tts_norm_sub(), see docs/tts-norm-patterns.md
|
||||
common_chat_tts_norm_add_builtins(ctx);
|
||||
jinja::global_from_json(ctx, vars, false);
|
||||
ctx.set_val("bos_token", jinja::mk_val<jinja::value_string>(tmpl.bos_token()));
|
||||
ctx.set_val("eos_token", jinja::mk_val<jinja::value_string>(tmpl.eos_token()));
|
||||
@@ -834,11 +827,6 @@ 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<std::string, std::string> names = {
|
||||
@@ -859,8 +847,7 @@ 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,
|
||||
double audio_length, const std::string & context) {
|
||||
common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language) {
|
||||
common_chat_prompt_preset asr_preset;
|
||||
asr_preset.system = "";
|
||||
asr_preset.user = "Transcribe audio to text";
|
||||
@@ -874,17 +861,6 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -892,7 +868,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 common_tts_g2p & g2p) {
|
||||
const std::string & language, const std::string & voice) {
|
||||
if (!chat_templates || !chat_templates->template_tts) {
|
||||
return "";
|
||||
}
|
||||
@@ -900,7 +876,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,
|
||||
@@ -979,11 +955,22 @@ 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;
|
||||
bool add_eos = false;
|
||||
common_peg_tokens specials;
|
||||
if (model) {
|
||||
const auto * vocab = llama_model_get_vocab(model);
|
||||
const auto get_token = [&](llama_token token, const char * name, const char * jinja_variable_name) {
|
||||
@@ -1003,13 +990,11 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model *
|
||||
token_eos = get_token(llama_vocab_eos(vocab), "EOS", "eos_token");
|
||||
add_bos = llama_vocab_get_add_bos(vocab);
|
||||
add_eos = llama_vocab_get_add_eos(vocab);
|
||||
specials = common_peg_tokens(vocab);
|
||||
}
|
||||
common_chat_templates_ptr tmpls(new common_chat_templates());
|
||||
tmpls->has_explicit_template = has_explicit_template;
|
||||
tmpls->add_bos = add_bos;
|
||||
tmpls->add_eos = add_eos;
|
||||
tmpls->specials = std::move(specials);
|
||||
try {
|
||||
tmpls->template_default = std::make_unique<common_chat_template>(default_template_src, token_bos, token_eos);
|
||||
} catch (const std::exception & e) {
|
||||
@@ -1034,25 +1019,6 @@ 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<common_tts_dicts>();
|
||||
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;
|
||||
}
|
||||
@@ -1473,12 +1439,6 @@ 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;
|
||||
}
|
||||
|
||||
@@ -1551,7 +1511,6 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_
|
||||
params.add_generation_prompt = inputs.add_generation_prompt;
|
||||
params.add_bos = tmpls->add_bos;
|
||||
params.add_eos = tmpls->add_eos;
|
||||
params.specials = tmpls->specials;
|
||||
|
||||
params.continue_final_message = inputs.continue_final_message;
|
||||
if (params.continue_final_message != COMMON_CHAT_CONTINUATION_NONE) {
|
||||
@@ -1834,7 +1793,6 @@ common_chat_input common_chat_input_tokenize(const llama_vocab * vocab, const st
|
||||
}
|
||||
if (input.text != text) {
|
||||
// the pieces do not give back the same text, keep the text without tokens
|
||||
LOG_WRN("%s: token pieces do not match the text, parsing without token ids\n", __func__);
|
||||
return common_chat_input(text);
|
||||
}
|
||||
return input;
|
||||
@@ -1945,17 +1903,11 @@ common_chat_session::common_chat_session(const common_chat_templates * tm
|
||||
thinking_ends = std::move(applied.thinking_end_tags);
|
||||
|
||||
parser_params.format = applied.format;
|
||||
parser_params.generation_prompt = vocab ? common_chat_input_tokenize(vocab, applied.generation_prompt)
|
||||
: common_chat_input(applied.generation_prompt);
|
||||
parser_params.debug = params.debug;
|
||||
parser_params.parser = std::move(applied.parser);
|
||||
|
||||
if (vocab) {
|
||||
parser_params.generation_prompt = common_chat_input_tokenize(vocab, applied.generation_prompt);
|
||||
} else if (params.tokenize) {
|
||||
parser_params.generation_prompt = params.tokenize(applied.generation_prompt);
|
||||
} else {
|
||||
parser_params.generation_prompt = common_chat_input(applied.generation_prompt);
|
||||
}
|
||||
|
||||
delimiters = std::move(applied.message_delimiters);
|
||||
|
||||
if (vocab) {
|
||||
@@ -2019,6 +1971,5 @@ 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;
|
||||
}
|
||||
|
||||
+3
-17
@@ -372,9 +372,6 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model *
|
||||
const std::string & bos_token_override = "",
|
||||
const std::string & eos_token_override = "");
|
||||
|
||||
// override special tokens for testing
|
||||
void common_chat_templates_set_specials(struct common_chat_templates * tmpls, common_peg_tokens specials);
|
||||
|
||||
bool common_chat_templates_was_explicit(const struct common_chat_templates * tmpls);
|
||||
std::string common_chat_templates_source(const struct common_chat_templates * tmpls, const std::string & variant = "");
|
||||
|
||||
@@ -400,9 +397,6 @@ common_chat_msg common_chat_peg_parse(const common_peg_arena & src_parser, const
|
||||
struct common_chat_session_params {
|
||||
bool echo = false; // include the assistant prefill in the output when continuing a message
|
||||
bool debug = false; // enable debug output for the PEG parser
|
||||
|
||||
// tokenize the generation prompt when there is no vocab for testing
|
||||
std::function<common_chat_input(const std::string &)> tokenize;
|
||||
};
|
||||
|
||||
class common_chat_session {
|
||||
@@ -497,23 +491,15 @@ std::optional<common_chat_params> 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_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
|
||||
bool has_language = false; // the preset already names the requested 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 = "");
|
||||
common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language = "");
|
||||
|
||||
// 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::function<std::string(const std::string & word)> & g2p = nullptr);
|
||||
const std::string & language = "", const std::string & voice = "");
|
||||
|
||||
// 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,
|
||||
|
||||
@@ -1313,11 +1313,6 @@ 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;
|
||||
@@ -2339,9 +2334,6 @@ 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;
|
||||
|
||||
+12
-25
@@ -174,20 +174,18 @@ 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_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_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_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
|
||||
@@ -416,12 +414,7 @@ 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 ||
|
||||
t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2 ||
|
||||
t == COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR;
|
||||
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 needs_rs_seq ? draft.n_max : 0u;
|
||||
@@ -702,7 +695,6 @@ struct common_params {
|
||||
// UI configs
|
||||
bool ui = true;
|
||||
bool ui_mcp_proxy = false;
|
||||
bool ui_mcp_proxy_allow_private_urls = false; // allow the MCP CORS proxy to reach local or private addresses
|
||||
std::string ui_config_json;
|
||||
|
||||
// "advanced" endpoints are disabled by default for better security
|
||||
@@ -797,7 +789,6 @@ 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
|
||||
};
|
||||
@@ -1003,9 +994,6 @@ 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
|
||||
@@ -1121,7 +1109,6 @@ struct common_batch {
|
||||
llama_embd state; // non-owning view of the data passed to set_embd_state(), data == NULL if none
|
||||
std::vector<llama_seq_id> 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
|
||||
};
|
||||
|
||||
+6
-20
@@ -98,9 +98,6 @@ class ProgressBar : public common_download_callback {
|
||||
std::string filename;
|
||||
size_t len = 0;
|
||||
|
||||
// the caller's callback, if any, still receives every event
|
||||
common_download_callback * next;
|
||||
|
||||
static void cleanup(const ProgressBar * line) {
|
||||
lines.erase(line);
|
||||
if (lines.empty()) {
|
||||
@@ -113,12 +110,9 @@ class ProgressBar : public common_download_callback {
|
||||
}
|
||||
|
||||
public:
|
||||
ProgressBar(common_download_callback * next) : next(next) {}
|
||||
ProgressBar() = default;
|
||||
|
||||
void on_start(const common_download_progress & p) override {
|
||||
if (next) {
|
||||
next->on_start(p);
|
||||
}
|
||||
filename = url_get_filename(p.url);
|
||||
|
||||
for (size_t i = 0; i < filename.size(); ++i) {
|
||||
@@ -132,22 +126,12 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
void on_done(const common_download_progress & p, bool ok) override {
|
||||
if (next) {
|
||||
next->on_done(p, ok);
|
||||
}
|
||||
void on_done(const common_download_progress &, bool) override {
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
cleanup(this);
|
||||
}
|
||||
|
||||
bool is_cancelled() const override {
|
||||
return next && next->is_cancelled();
|
||||
}
|
||||
|
||||
void on_update(const common_download_progress & p) override {
|
||||
if (next) {
|
||||
next->on_update(p);
|
||||
}
|
||||
if (!p.total || !is_output_a_tty()) {
|
||||
return;
|
||||
}
|
||||
@@ -535,9 +519,11 @@ int common_download_file_single(const std::string & url,
|
||||
const std::string & lock_path,
|
||||
const std::string & alt_path) {
|
||||
if (!opts.offline) {
|
||||
ProgressBar tty_cb(opts.callback);
|
||||
ProgressBar tty_cb;
|
||||
common_download_opts online_opts = opts;
|
||||
online_opts.callback = &tty_cb;
|
||||
if (!online_opts.callback) {
|
||||
online_opts.callback = &tty_cb;
|
||||
}
|
||||
return common_download_file_single_online(url, path, online_opts, skip_etag, lock_path, alt_path);
|
||||
}
|
||||
|
||||
|
||||
+2
-15
@@ -593,7 +593,7 @@ caps caps_get(jinja::program & prog) {
|
||||
if (result.supports_reasoning_effort) {
|
||||
JJ_DEBUG("%s\n", ">>> Running capability check: reasoning effort levels");
|
||||
|
||||
static const std::vector<std::string> candidates = { "none", "minimal", "low", "medium", "high", "xhigh", "max" };
|
||||
static const std::vector<std::string> candidates = { "minimal", "low", "medium", "high", "xhigh", "max" };
|
||||
|
||||
// renders a single user turn with the given effort, nothing when the template raises
|
||||
const auto render = [&](const std::string & effort) {
|
||||
@@ -627,17 +627,9 @@ 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<std::string> renders;
|
||||
std::vector<std::string> rejected;
|
||||
for (const auto & level : candidates) {
|
||||
const auto rendered = render(level);
|
||||
if (!rendered) {
|
||||
// "none" also turns thinking off, so the server does not answer it with an error
|
||||
if (level != "none") {
|
||||
rejected.push_back(level);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (rendered == unknown) {
|
||||
if (!rendered || rendered == unknown) {
|
||||
continue;
|
||||
}
|
||||
const auto it = std::find(renders.begin(), renders.end(), *rendered);
|
||||
@@ -648,11 +640,6 @@ 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());
|
||||
|
||||
@@ -23,9 +23,6 @@ struct caps {
|
||||
// reasoning effort levels the template renders distinctly, from lowest to highest
|
||||
std::vector<std::string> reasoning_effort_levels;
|
||||
|
||||
// reasoning effort levels the template raises on
|
||||
std::vector<std::string> reasoning_effort_rejected;
|
||||
|
||||
// one of the 2 content capabilities must be true
|
||||
bool supports_string_content = true;
|
||||
bool supports_typed_content = false;
|
||||
|
||||
@@ -263,6 +263,41 @@ 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) {
|
||||
|
||||
@@ -39,6 +39,7 @@ struct token {
|
||||
multiplicative_binary_operator, // * / %
|
||||
power_operator, // **
|
||||
comparison_binary_operator, // < > <= >= == !=
|
||||
unary_operator, // ! - +
|
||||
comment, // {# ... #}
|
||||
};
|
||||
type t;
|
||||
@@ -73,6 +74,7 @@ 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";
|
||||
}
|
||||
@@ -139,7 +141,6 @@ 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
|
||||
|
||||
@@ -482,8 +482,7 @@ private:
|
||||
}
|
||||
|
||||
statement_ptr parse_unary_expression() {
|
||||
// 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 != "~") {
|
||||
if (is(token::unary_operator)) {
|
||||
depth_guard guard(*this);
|
||||
size_t start_pos = current;
|
||||
auto op = next();
|
||||
|
||||
+48
-94
@@ -89,22 +89,21 @@ value statement::execute(context & ctx) const {
|
||||
}
|
||||
|
||||
value identifier::execute_impl(context & ctx) const {
|
||||
auto it = ctx.find_val(key);
|
||||
if (it && !it->is_undefined()) {
|
||||
auto it = ctx.get_val(val);
|
||||
auto builtins = global_builtins();
|
||||
if (!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;
|
||||
}
|
||||
const auto & builtins = global_builtins();
|
||||
auto builtin = builtins.find(val);
|
||||
if (builtin != builtins.end()) {
|
||||
} else if (builtins.find(val) != builtins.end()) {
|
||||
JJ_DEBUG("Identifier '%s' found in builtins", val.c_str());
|
||||
return mk_val<value_func>(val, builtin->second);
|
||||
return mk_val<value_func>(val, builtins.at(val));
|
||||
} else {
|
||||
JJ_DEBUG("Identifier '%s' not found, returning undefined", val.c_str());
|
||||
return mk_val<value_undefined>(val);
|
||||
}
|
||||
JJ_DEBUG("Identifier '%s' not found, returning undefined", val.c_str());
|
||||
return mk_val<value_undefined>(val);
|
||||
}
|
||||
|
||||
value object_literal::execute_impl(context & ctx) const {
|
||||
@@ -191,30 +190,11 @@ static value exec_binary_op(context & ctx, const token & op, value left_val, val
|
||||
if (is_float) {
|
||||
return mk_val<value_float>(res);
|
||||
} else {
|
||||
return mk_val<value_int>(float_to_int(res));
|
||||
return mk_val<value_int>(static_cast<int64_t>(res));
|
||||
}
|
||||
} else if (op.value == "/") {
|
||||
JJ_DEBUG("Division operation: %f / %f", a, b);
|
||||
return mk_val<value_float>(a / b);
|
||||
} else if (op.value == "//") {
|
||||
// python semantics: round toward -inf
|
||||
if (is_val<value_int>(left_val) && is_val<value_int>(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<value_int>((int64_t) (0 - (uint64_t) x));
|
||||
}
|
||||
int64_t q = x / y;
|
||||
if (x % y != 0 && (x < 0) != (y < 0)) {
|
||||
q -= 1;
|
||||
}
|
||||
return mk_val<value_int>(q);
|
||||
}
|
||||
return mk_val<value_float>(std::floor(a / b));
|
||||
} else if (op.value == "%") {
|
||||
double rem = std::fmod(a, b);
|
||||
JJ_DEBUG("Modulo operation: %f %% %f = %f", a, b, rem);
|
||||
@@ -222,7 +202,7 @@ static value exec_binary_op(context & ctx, const token & op, value left_val, val
|
||||
if (is_float) {
|
||||
return mk_val<value_float>(rem);
|
||||
} else {
|
||||
return mk_val<value_int>(float_to_int(rem));
|
||||
return mk_val<value_int>(static_cast<int64_t>(rem));
|
||||
}
|
||||
} else if (op.value == "<") {
|
||||
JJ_DEBUG("Comparison operation: %f < %f is %d", a, b, a < b);
|
||||
@@ -293,17 +273,12 @@ static value exec_binary_op(context & ctx, const token & op, value left_val, val
|
||||
// String membership
|
||||
if (is_val<value_string>(left_val) && is_val<value_string>(right_val)) {
|
||||
// case: "a" in "abc"
|
||||
if (op.value == "in" || op.value == "not in") {
|
||||
bool member = test_is_in();
|
||||
return mk_val<value_bool>(op.value == "in" ? member : !member);
|
||||
bool member = test_is_in();
|
||||
if (op.value == "in") {
|
||||
return mk_val<value_bool>(member);
|
||||
} else if (op.value == "not in") {
|
||||
return mk_val<value_bool>(!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<value_bool>(a < b); }
|
||||
if (op.value == ">") { return mk_val<value_bool>(a > b); }
|
||||
if (op.value == "<=") { return mk_val<value_bool>(a <= b); }
|
||||
if (op.value == ">=") { return mk_val<value_bool>(a >= b); }
|
||||
}
|
||||
|
||||
// Value key in object
|
||||
@@ -718,7 +693,7 @@ value set_statement::execute_impl(context & ctx) const {
|
||||
}
|
||||
auto obj_ptr = cast_val<value_object>(object);
|
||||
JJ_DEBUG("Setting object property '%s' with value type %s", prop_name.c_str(), rhs->type().c_str());
|
||||
obj_ptr->insert(cached_val<value_string>(ctx, member->static_property), rhs);
|
||||
obj_ptr->insert(prop_name, rhs);
|
||||
|
||||
} else {
|
||||
throw std::runtime_error("Invalid LHS inside assignment expression: " + assignee->type());
|
||||
@@ -811,14 +786,13 @@ value call_statement::execute_impl(context & ctx) const {
|
||||
}
|
||||
auto * callee_func = cast_val<value_func>(callee_val);
|
||||
|
||||
// caller() can be saved and called after this scope ended, it owns a snapshot of the variables
|
||||
auto caller_ctx = std::make_shared<context>(ctx.snapshot());
|
||||
context caller_ctx(ctx); // new scope for caller execution
|
||||
|
||||
const func_handler func = [this, caller_ctx](const func_args & args) -> value {
|
||||
const func_handler func = [this, caller_ctx = std::move(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);
|
||||
@@ -839,19 +813,6 @@ 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<expression>(this->object);
|
||||
chk_type<expression>(this->property);
|
||||
if (!computed) {
|
||||
if (const auto * id = cast_stmt<identifier>(this->property)) {
|
||||
static_property = id->key;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
value member_expression::execute_impl(context & ctx) const {
|
||||
value object = this->object->execute(ctx);
|
||||
|
||||
@@ -860,13 +821,14 @@ 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<value_array>(object)) {
|
||||
arr_size = object->as_array().size();
|
||||
} else if (is_val<value_string>(object)) {
|
||||
arr_size = object->as_string().length();
|
||||
}
|
||||
|
||||
if (is_stmt<slice_expression>(this->property)) {
|
||||
int64_t arr_size = 0;
|
||||
if (is_val<value_array>(object)) {
|
||||
arr_size = static_cast<int64_t>(object->as_array().size());
|
||||
} else if (is_val<value_string>(object)) {
|
||||
arr_size = static_cast<int64_t>(cast_val<value_string>(object)->val_str.length());
|
||||
}
|
||||
auto s = cast_stmt<slice_expression>(this->property);
|
||||
value step_val = s->step_expr ? s->step_expr->execute(ctx) : mk_val<value_int>(1);
|
||||
value start_val = s->start_expr ? s->start_expr->execute(ctx) : (step_val->as_int() < 0 ? mk_val<value_int>(arr_size - 1) : mk_val<value_int>(0));
|
||||
@@ -888,7 +850,7 @@ value member_expression::execute_impl(context & ctx) const {
|
||||
}
|
||||
} else if (is_stmt<integer_literal>(this->property)) {
|
||||
// syntax: obj.index
|
||||
property = this->property->execute(ctx);
|
||||
property = mk_val<value_int>(cast_stmt<integer_literal>(this->property)->val);
|
||||
if (property->as_int() < 0) {
|
||||
throw std::runtime_error("Static member property cannot be negative");
|
||||
}
|
||||
@@ -897,8 +859,8 @@ value member_expression::execute_impl(context & ctx) const {
|
||||
if (!is_stmt<identifier>(this->property)) {
|
||||
throw std::runtime_error("Static member property must be an identifier");
|
||||
}
|
||||
property = cached_val<value_string>(ctx, static_property);
|
||||
const auto & prop = cast_stmt<identifier>(this->property)->val;
|
||||
property = mk_val<value_string>(cast_stmt<identifier>(this->property)->val);
|
||||
std::string prop = property->as_string().str();
|
||||
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,
|
||||
@@ -906,56 +868,51 @@ 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 = find_builtin_func(ctx, prop, object);
|
||||
if (val) {
|
||||
value val = try_builtin_func(ctx, prop, object, true);
|
||||
if (!is_val<value_undefined>(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;
|
||||
value val = mk_val<value_undefined>("object_property");
|
||||
|
||||
if (property->is_undefined()) {
|
||||
JJ_DEBUG("%s", "Member expression property is undefined, returning undefined");
|
||||
return mk_val<value_undefined>("object_property");
|
||||
return val;
|
||||
}
|
||||
|
||||
ensure_key_type_allowed(property);
|
||||
|
||||
if (is_val<value_undefined>(object)) {
|
||||
JJ_DEBUG("%s", "Accessing property on undefined object, returning undefined");
|
||||
return mk_val<value_undefined>("object_property");
|
||||
return val;
|
||||
|
||||
} else if (is_val<value_object>(object)) {
|
||||
val = object->find(property);
|
||||
if (!val || is_val<value_undefined>(val)) {
|
||||
val = try_builtin_func(ctx, property->as_string().str(), object, true);
|
||||
auto key = property->as_string().str();
|
||||
val = object->at(property, val);
|
||||
if (is_val<value_undefined>(val)) {
|
||||
val = try_builtin_func(ctx, key, object, true);
|
||||
}
|
||||
JJ_DEBUG("Accessed property '%s' value, got type: %s", property->as_string().str().c_str(), val->type().c_str());
|
||||
JJ_DEBUG("Accessed property '%s' value, got type: %s", key.c_str(), val->type().c_str());
|
||||
|
||||
} else if (is_val<value_array>(object) || is_val<value_string>(object)) {
|
||||
if (is_val<value_int>(property) || is_val<value_bool>(property)) {
|
||||
int64_t index = property->as_int();
|
||||
JJ_DEBUG("Accessing %s index %d", object->type().c_str(), (int)index);
|
||||
if (is_val<value_array>(object)) {
|
||||
const auto * arr = cast_val<value_array>(object);
|
||||
const auto count = arr->as_array().size();
|
||||
auto & arr = object->as_array();
|
||||
if (index < 0) {
|
||||
// Avoid negating INT64_MIN.
|
||||
const uint64_t distance = static_cast<uint64_t>(-(index + 1)) + 1;
|
||||
if (distance <= count) {
|
||||
val = arr->as_array().at(static_cast<size_t>(count - distance));
|
||||
}
|
||||
} else if (static_cast<uint64_t>(index) < count) {
|
||||
val = arr->as_array().at(static_cast<size_t>(index));
|
||||
index += static_cast<int64_t>(arr.size());
|
||||
}
|
||||
if (index >= 0 && index < static_cast<int64_t>(arr.size())) {
|
||||
val = arr[index];
|
||||
}
|
||||
} else { // value_string
|
||||
if (index >= 0) {
|
||||
const auto byte = cast_val<value_string>(object)->val_str.byte_at(static_cast<size_t>(index));
|
||||
if (byte) {
|
||||
val = mk_val<value_string>(std::string(1, *byte));
|
||||
}
|
||||
auto str = object->as_string().str();
|
||||
if (index >= 0 && index < static_cast<int64_t>(str.size())) {
|
||||
val = mk_val<value_string>(std::string(1, str[index]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -973,10 +930,7 @@ value member_expression::execute_impl(context & ctx) const {
|
||||
val = try_builtin_func(ctx, key, object, true);
|
||||
}
|
||||
|
||||
if (!val) {
|
||||
val = mk_val<value_undefined>("object_property");
|
||||
}
|
||||
if (ctx.is_get_stats && object && property) {
|
||||
if (ctx.is_get_stats && val && object && property) {
|
||||
value_t::stats_t::mark_used(val);
|
||||
value_t::stats_t::mark_used(object);
|
||||
value_t::stats_t::mark_used(property);
|
||||
|
||||
+20
-59
@@ -81,43 +81,12 @@ struct context {
|
||||
current_time(parent.current_time),
|
||||
is_get_stats(parent.is_get_stats),
|
||||
macro_depth(parent.macro_depth),
|
||||
// child scope: own variables only, lookups fall back to the parent (which must outlive this scope)
|
||||
parent(&parent),
|
||||
env(mk_val<value_object>()) {
|
||||
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<const context *> 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;
|
||||
}
|
||||
// inherit variables (for example, when entering a new scope)
|
||||
env(mk_val<value_object>(*parent.env)) {}
|
||||
|
||||
value get_val(const std::string & name) {
|
||||
auto result = find_val(mk_val<value_string>(name));
|
||||
return result ? result : mk_val<value_undefined>(name);
|
||||
value default_val = mk_val<value_undefined>(name);
|
||||
return env->at(name, default_val);
|
||||
}
|
||||
|
||||
void set_val(const std::string & name, const value & val) {
|
||||
@@ -133,16 +102,9 @@ 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<typename T>
|
||||
value cached_val(const context & ctx, const value & cached) {
|
||||
return ctx.is_get_stats ? mk_val<T>(*cast_val<T>(cached)) : cached;
|
||||
}
|
||||
|
||||
// utils for visiting AST nodes
|
||||
static std::vector<const statement *> stmts_to_ptr(const statements & stmts) {
|
||||
std::vector<const statement *> children;
|
||||
@@ -366,8 +328,11 @@ struct member_expression : public expression {
|
||||
statement_ptr property;
|
||||
bool computed; // true if obj[expr] and false if obj.prop
|
||||
|
||||
value static_property; // set if property is an identifier, see cached_val()
|
||||
member_expression(statement_ptr && object, statement_ptr && property, bool computed);
|
||||
member_expression(statement_ptr && object, statement_ptr && property, bool computed)
|
||||
: object(std::move(object)), property(std::move(property)), computed(computed) {
|
||||
chk_type<expression>(this->object);
|
||||
chk_type<expression>(this->property);
|
||||
}
|
||||
std::string type() const override { return "MemberExpression"; }
|
||||
value execute_impl(context & ctx) const override;
|
||||
void visit(context & ctx) const override {
|
||||
@@ -402,8 +367,7 @@ struct call_expression : public expression {
|
||||
*/
|
||||
struct identifier : public expression {
|
||||
std::string 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<value_string>(val)) {}
|
||||
explicit identifier(const std::string & val) : val(val) {}
|
||||
std::string type() const override { return "Identifier"; }
|
||||
value execute_impl(context & ctx) const override;
|
||||
};
|
||||
@@ -412,31 +376,28 @@ struct identifier : public expression {
|
||||
|
||||
struct integer_literal : public expression {
|
||||
int64_t val;
|
||||
const value constant; // see cached_val()
|
||||
explicit integer_literal(int64_t val) : val(val), constant(mk_val<value_int>(val)) {}
|
||||
explicit integer_literal(int64_t val) : val(val) {}
|
||||
std::string type() const override { return "IntegerLiteral"; }
|
||||
value execute_impl(context & ctx) const override {
|
||||
return cached_val<value_int>(ctx, constant);
|
||||
value execute_impl(context &) const override {
|
||||
return mk_val<value_int>(val);
|
||||
}
|
||||
};
|
||||
|
||||
struct float_literal : public expression {
|
||||
double val;
|
||||
const value constant; // see cached_val()
|
||||
explicit float_literal(double val) : val(val), constant(mk_val<value_float>(val)) {}
|
||||
explicit float_literal(double val) : val(val) {}
|
||||
std::string type() const override { return "FloatLiteral"; }
|
||||
value execute_impl(context & ctx) const override {
|
||||
return cached_val<value_float>(ctx, constant);
|
||||
value execute_impl(context &) const override {
|
||||
return mk_val<value_float>(val);
|
||||
}
|
||||
};
|
||||
|
||||
struct string_literal : public expression {
|
||||
std::string val;
|
||||
const value constant; // see cached_val()
|
||||
explicit string_literal(const std::string & val) : val(val), constant(mk_val<value_string>(val)) {}
|
||||
explicit string_literal(const std::string & val) : val(val) {}
|
||||
std::string type() const override { return "StringLiteral"; }
|
||||
value execute_impl(context & ctx) const override {
|
||||
return cached_val<value_string>(ctx, constant);
|
||||
value execute_impl(context &) const override {
|
||||
return mk_val<value_string>(val);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -787,7 +748,7 @@ static void gather_string_parts_recursive(const value & val, value_string & part
|
||||
} else if (is_val<value_array>(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<value_array>(val)) {
|
||||
const auto & items = cast_val<value_array>(val)->as_array();
|
||||
auto items = cast_val<value_array>(val)->as_array();
|
||||
for (const auto & item : items) {
|
||||
gather_string_parts_recursive(item, parts, depth + 1);
|
||||
}
|
||||
|
||||
+6
-51
@@ -43,59 +43,14 @@ void string::mark_input() {
|
||||
}
|
||||
|
||||
std::string string::str() const {
|
||||
std::string result;
|
||||
result.reserve(length());
|
||||
if (parts.size() == 1) {
|
||||
return parts[0].val;
|
||||
}
|
||||
std::ostringstream oss;
|
||||
for (const auto & part : parts) {
|
||||
result += part.val;
|
||||
oss << part.val;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool string::empty() const {
|
||||
for (const auto & part : parts) {
|
||||
if (!part.val.empty()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<char> string::byte_at(size_t index) const {
|
||||
for (const auto & part : parts) {
|
||||
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 part == other.parts.size();
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
size_t string::length() const {
|
||||
|
||||
@@ -39,9 +39,6 @@ struct string {
|
||||
|
||||
std::string str() const;
|
||||
size_t length() const;
|
||||
bool empty() const;
|
||||
bool equals(const string & other) const;
|
||||
std::optional<char> byte_at(size_t index) const;
|
||||
void hash_update(hasher & hash) const noexcept;
|
||||
bool all_parts_are_input() const;
|
||||
bool is_uppercase() const;
|
||||
|
||||
+33
-77
@@ -276,17 +276,19 @@ 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(val_input, true);
|
||||
value_t::stats_t::mark_used(const_cast<value&>(val_input), true);
|
||||
}
|
||||
if (is_val<value_int>(val_indent)) {
|
||||
indent = static_cast<int>(val_indent->as_int());
|
||||
}
|
||||
const bool sort_keys = val_sort->as_bool(); // undefined == false
|
||||
if (val_sort->as_bool()) { // undefined == false
|
||||
throw not_implemented_exception("tojson sort_keys=true not implemented");
|
||||
}
|
||||
const bool ensure_ascii = val_ascii->as_bool(); // undefined == false
|
||||
auto separators = (is_val<value_array>(val_separators) ? val_separators : mk_val<value_array>())->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, sort_keys);
|
||||
std::string json_str = value_to_json(args.get_pos(0), indent, item_sep, key_sep);
|
||||
if (ensure_ascii) {
|
||||
json_str = json_ensure_ascii_preserving_format(json_str);
|
||||
}
|
||||
@@ -505,12 +507,7 @@ const func_builtins & global_builtins() {
|
||||
}},
|
||||
{"test_is_divisibleby", [](const func_args & args) -> value {
|
||||
args.ensure_vals<value_int, value_int>();
|
||||
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
|
||||
bool res = args.get_pos(0)->val_int % args.get_pos(1)->val_int == 0;
|
||||
return mk_val<value_bool>(res);
|
||||
}},
|
||||
{"test_is_string", test_type_fn<value_string>},
|
||||
@@ -522,11 +519,11 @@ const func_builtins & global_builtins() {
|
||||
{"test_is_mapping", test_type_fn<value_object>},
|
||||
{"test_is_lower", [](const func_args & args) -> value {
|
||||
args.ensure_vals<value_string>();
|
||||
return mk_val<value_bool>(cast_val<value_string>(args.get_pos(0))->val_str.is_lowercase());
|
||||
return mk_val<value_bool>(args.get_pos(0)->val_str.is_lowercase());
|
||||
}},
|
||||
{"test_is_upper", [](const func_args & args) -> value {
|
||||
args.ensure_vals<value_string>();
|
||||
return mk_val<value_bool>(cast_val<value_string>(args.get_pos(0))->val_str.is_uppercase());
|
||||
return mk_val<value_bool>(args.get_pos(0)->val_str.is_uppercase());
|
||||
}},
|
||||
{"test_is_none", test_type_fn<value_none>},
|
||||
{"test_is_defined", [](const func_args & args) -> value {
|
||||
@@ -574,7 +571,7 @@ const func_builtins & global_builtins() {
|
||||
{"test_is_test", [](const func_args & args) -> value {
|
||||
args.ensure_vals<value_string>();
|
||||
auto & builtins = global_builtins();
|
||||
std::string test_name = cast_val<value_string>(args.get_pos(0))->val_str.str();
|
||||
std::string test_name = args.get_pos(0)->val_str.str();
|
||||
auto it = builtins.find("test_is_" + test_name);
|
||||
bool res = it != builtins.end();
|
||||
return mk_val<value_bool>(res);
|
||||
@@ -616,26 +613,18 @@ const func_builtins & global_builtins() {
|
||||
return builtins;
|
||||
}
|
||||
|
||||
value find_builtin_func(context & ctx, const std::string & name, value & input) {
|
||||
value try_builtin_func(context & ctx, const std::string & name, value & input, bool undef_on_missing) {
|
||||
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);
|
||||
}
|
||||
const auto & builtins = input->get_builtins();
|
||||
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<value_func>(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<value_undefined>(name);
|
||||
}
|
||||
@@ -711,7 +700,7 @@ const func_builtins & value_float_t::get_builtins() const {
|
||||
}},
|
||||
{"int", [](const func_args & args) -> value {
|
||||
args.ensure_vals<value_float>();
|
||||
int64_t val = float_to_int(args.get_pos(0)->as_float());
|
||||
int64_t val = static_cast<int64_t>(args.get_pos(0)->as_float());
|
||||
return mk_val<value_int>(val);
|
||||
}},
|
||||
{"float", [](const func_args & args) -> value {
|
||||
@@ -842,7 +831,7 @@ const func_builtins & value_string_t::get_builtins() const {
|
||||
--maxsplit;
|
||||
}
|
||||
auto res = mk_val<value_string>(str);
|
||||
res->val_str.mark_input_based_on(cast_val<value_string>(args.get_pos(0))->val_str);
|
||||
res->val_str.mark_input_based_on(args.get_pos(0)->val_str);
|
||||
result->push_back(std::move(res));
|
||||
return result;
|
||||
}},
|
||||
@@ -869,7 +858,7 @@ const func_builtins & value_string_t::get_builtins() const {
|
||||
--maxsplit;
|
||||
}
|
||||
auto res = mk_val<value_string>(str);
|
||||
res->val_str.mark_input_based_on(cast_val<value_string>(args.get_pos(0))->val_str);
|
||||
res->val_str.mark_input_based_on(args.get_pos(0)->val_str);
|
||||
result->push_back(std::move(res));
|
||||
result->reverse();
|
||||
return result;
|
||||
@@ -902,7 +891,7 @@ const func_builtins & value_string_t::get_builtins() const {
|
||||
}
|
||||
}
|
||||
auto res = mk_val<value_string>(str);
|
||||
res->val_str.mark_input_based_on(cast_val<value_string>(args.get_pos(0))->val_str);
|
||||
res->val_str.mark_input_based_on(args.get_pos(0)->val_str);
|
||||
return res;
|
||||
}},
|
||||
{"format", [](const func_args & args) -> value {
|
||||
@@ -1099,28 +1088,8 @@ const func_builtins & value_bool_t::get_builtins() const {
|
||||
return builtins;
|
||||
}
|
||||
|
||||
static value array_sum(const func_args & args) {
|
||||
args.ensure_kwargs({"attribute", "start"});
|
||||
args.ensure_count(1, 3);
|
||||
args.ensure_vals<value_array>();
|
||||
value undef = mk_val<value_undefined>();
|
||||
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<value_float>(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<value_int>(v) && !is_val<value_float>(v)) {
|
||||
throw raised_exception("sum: unsupported operand type " + v->type());
|
||||
}
|
||||
is_float = is_float || is_val<value_float>(v);
|
||||
sum += v->as_float();
|
||||
}
|
||||
return is_float ? value(mk_val<value_float>(sum)) : value(mk_val<value_int>(float_to_int(sum)));
|
||||
[[noreturn]] static value array_sum_not_implemented(const func_args &) {
|
||||
throw not_implemented_exception("Array sum builtin not implemented");
|
||||
}
|
||||
|
||||
const func_builtins & value_array_t::get_builtins() const {
|
||||
@@ -1189,7 +1158,7 @@ const func_builtins & value_array_t::get_builtins() const {
|
||||
{"select", select_or_reject<false, false>},
|
||||
{"rejectattr", select_or_reject<true, true>},
|
||||
{"reject", select_or_reject<true, false>},
|
||||
{"sum", array_sum},
|
||||
{"sum", array_sum_not_implemented},
|
||||
{"join", [](const func_args & args) -> value {
|
||||
args.ensure_kwargs({"d", "attribute"});
|
||||
args.ensure_count(1, 3);
|
||||
@@ -1222,7 +1191,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(val_input, true);
|
||||
value_t::stats_t::mark_used(const_cast<value&>(val_input), true);
|
||||
}
|
||||
return mk_val<value_string>(args.get_pos(0)->as_string());
|
||||
}},
|
||||
@@ -1470,7 +1439,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(val_input, true);
|
||||
value_t::stats_t::mark_used(const_cast<value&>(val_input), true);
|
||||
}
|
||||
return mk_val<value_string>(args.get_pos(0)->as_string());
|
||||
}},
|
||||
@@ -1674,11 +1643,6 @@ 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());
|
||||
@@ -1764,7 +1728,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, bool sort_keys) {
|
||||
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) {
|
||||
auto indent_str = [indent, curr_lvl]() -> std::string {
|
||||
return (indent > 0) ? std::string(curr_lvl * indent, ' ') : "";
|
||||
};
|
||||
@@ -1811,7 +1775,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, sort_keys);
|
||||
value_to_json_internal(oss, arr[i], curr_lvl + 1, indent, item_sep, key_sep);
|
||||
if (i < arr.size() - 1) {
|
||||
oss << item_sep;
|
||||
}
|
||||
@@ -1822,25 +1786,17 @@ static void value_to_json_internal(std::ostringstream & oss, const value & val,
|
||||
oss << "]";
|
||||
} else if (is_val<value_object>(val)) {
|
||||
const auto & obj = val->as_ordered_object(); // IMPORTANT: need to keep exact order
|
||||
std::vector<std::pair<std::string, value>> items;
|
||||
items.reserve(obj.size());
|
||||
for (const auto & pair : obj) {
|
||||
items.emplace_back(is_val<value_float>(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 (!items.empty()) {
|
||||
if (!obj.empty()) {
|
||||
oss << newline();
|
||||
size_t i = 0;
|
||||
for (const auto & [key, item] : items) {
|
||||
for (const auto & pair : obj) {
|
||||
oss << indent_str() << (indent > 0 ? std::string(indent, ' ') : "");
|
||||
value_to_json_internal(oss, mk_val<value_string>(key), curr_lvl + 1, indent, item_sep, key_sep, sort_keys);
|
||||
const std::string key = is_val<value_float>(pair.first) ? float_json(pair.first->as_float()) : pair.first->as_string().str();
|
||||
value_to_json_internal(oss, mk_val<value_string>(key), curr_lvl + 1, indent, item_sep, key_sep);
|
||||
oss << key_sep;
|
||||
value_to_json_internal(oss, item, curr_lvl + 1, indent, item_sep, key_sep, sort_keys);
|
||||
if (i < items.size() - 1) {
|
||||
value_to_json_internal(oss, pair.second, curr_lvl + 1, indent, item_sep, key_sep);
|
||||
if (i < obj.size() - 1) {
|
||||
oss << item_sep;
|
||||
}
|
||||
oss << newline();
|
||||
@@ -1854,9 +1810,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, bool sort_keys) {
|
||||
std::string value_to_json(const value & val, int indent, const std::string_view item_sep, const std::string_view key_sep) {
|
||||
std::ostringstream oss;
|
||||
value_to_json_internal(oss, val, 0, indent, item_sep, key_sep, sort_keys);
|
||||
value_to_json_internal(oss, val, 0, indent, item_sep, key_sep);
|
||||
JJ_DEBUG("value_to_json: result=%s", oss.str().c_str());
|
||||
return oss.str();
|
||||
}
|
||||
@@ -1877,18 +1833,18 @@ std::string value_to_string_repr(const value & val) {
|
||||
}
|
||||
|
||||
// stats utility
|
||||
void value_t::stats_t::mark_used(const value & val, bool deep, int depth) {
|
||||
void value_t::stats_t::mark_used(value & val, bool deep, int depth) {
|
||||
val->stats.used = true;
|
||||
if (deep && (is_val<value_array>(val) || is_val<value_object>(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<value_array>(val)) {
|
||||
for (auto & item : val->as_array()) {
|
||||
for (auto & item : val->val_arr) {
|
||||
mark_used(item, deep, depth + 1);
|
||||
}
|
||||
} else if (is_val<value_object>(val)) {
|
||||
for (auto & pair : val->as_ordered_object()) {
|
||||
for (auto & pair : val->val_obj) {
|
||||
mark_used(pair.first, deep, depth + 1);
|
||||
mark_used(pair.second, deep, depth + 1);
|
||||
}
|
||||
|
||||
+90
-142
@@ -21,20 +21,6 @@ namespace jinja {
|
||||
struct value_t;
|
||||
using value = std::shared_ptr<value_t>;
|
||||
|
||||
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<typename T>
|
||||
@@ -48,12 +34,12 @@ struct extract_pointee<std::shared_ptr<U>> {
|
||||
template<typename T>
|
||||
bool is_val(const value & ptr) {
|
||||
using PointeeType = typename extract_pointee<T>::type;
|
||||
return has_value_kind(ptr.get(), PointeeType::kind_id);
|
||||
return dynamic_cast<const PointeeType*>(ptr.get()) != nullptr;
|
||||
}
|
||||
template<typename T>
|
||||
bool is_val(const value_t * ptr) {
|
||||
using PointeeType = typename extract_pointee<T>::type;
|
||||
return has_value_kind(ptr, PointeeType::kind_id);
|
||||
return dynamic_cast<const PointeeType*>(ptr) != nullptr;
|
||||
}
|
||||
template<typename T, typename... Args>
|
||||
std::shared_ptr<typename extract_pointee<T>::type> mk_val(Args&&... args) {
|
||||
@@ -63,12 +49,12 @@ std::shared_ptr<typename extract_pointee<T>::type> mk_val(Args&&... args) {
|
||||
template<typename T>
|
||||
const typename extract_pointee<T>::type * cast_val(const value & ptr) {
|
||||
using PointeeType = typename extract_pointee<T>::type;
|
||||
return is_val<T>(ptr) ? static_cast<const PointeeType *>(ptr.get()) : nullptr;
|
||||
return dynamic_cast<const PointeeType*>(ptr.get());
|
||||
}
|
||||
template<typename T>
|
||||
typename extract_pointee<T>::type * cast_val(value & ptr) {
|
||||
using PointeeType = typename extract_pointee<T>::type;
|
||||
return is_val<T>(ptr) ? static_cast<PointeeType *>(ptr.get()) : nullptr;
|
||||
return dynamic_cast<PointeeType*>(ptr.get());
|
||||
}
|
||||
// End Helper
|
||||
|
||||
@@ -105,10 +91,6 @@ struct context; // forward declaration
|
||||
template<typename T_JSON>
|
||||
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<typename T_JSON>
|
||||
value value_from_json(const T_JSON & json_val, bool mark_input);
|
||||
|
||||
//
|
||||
// base value type
|
||||
//
|
||||
@@ -123,7 +105,14 @@ 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 {
|
||||
const value_kind kind;
|
||||
int64_t val_int;
|
||||
double val_flt;
|
||||
string val_str;
|
||||
|
||||
std::vector<value> val_arr;
|
||||
std::vector<std::pair<value, value>> val_obj;
|
||||
|
||||
func_handler val_func;
|
||||
|
||||
// only used if ctx.is_get_stats = true
|
||||
struct stats_t {
|
||||
@@ -131,10 +120,10 @@ struct value_t {
|
||||
// ops can be builtin calls or operators: "array_access", "object_access"
|
||||
std::set<std::string> ops;
|
||||
// utility to recursively mark value and its children as used
|
||||
static void mark_used(const value & val, bool deep = false, int depth = 0);
|
||||
static void mark_used(value & val, bool deep = false, int depth = 0);
|
||||
} stats;
|
||||
|
||||
explicit value_t(value_kind kind) : kind(kind) {}
|
||||
value_t() = default;
|
||||
value_t(const value_t &) = default;
|
||||
virtual ~value_t() = default;
|
||||
|
||||
@@ -152,10 +141,6 @@ 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"); }
|
||||
@@ -187,23 +172,15 @@ protected:
|
||||
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 = ": ", bool sort_keys = false);
|
||||
std::string value_to_json(const value & val, int indent = -1, const std::string_view item_sep = ", ", const std::string_view key_sep = ": ");
|
||||
|
||||
// Note: only used for debugging purposes
|
||||
std::string value_to_string_repr(const value & val);
|
||||
@@ -237,28 +214,11 @@ 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<int64_t>(v);
|
||||
}
|
||||
|
||||
struct value_int_t : public value_t {
|
||||
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) {
|
||||
value_int_t(int64_t v) {
|
||||
val_int = v;
|
||||
val_flt = static_cast<double>(v);
|
||||
if (float_to_int(val_flt) != v) {
|
||||
if (static_cast<int64_t>(val_flt) != v) {
|
||||
val_flt = v < 0 ? -INFINITY : INFINITY;
|
||||
}
|
||||
}
|
||||
@@ -279,22 +239,21 @@ struct value_int_t : public value_t {
|
||||
}
|
||||
protected:
|
||||
virtual bool equivalent(const value_t & other) const override {
|
||||
return other.is_numeric() && val_int == other.as_int() && val_flt == other.as_float();
|
||||
return other.is_numeric() && val_int == other.val_int && val_flt == other.val_flt;
|
||||
}
|
||||
virtual bool nonequal(const value_t & other) const override {
|
||||
return !(kind == other.kind && val_int == other.as_int());
|
||||
return !(typeid(*this) == typeid(other) && val_int == other.val_int);
|
||||
}
|
||||
};
|
||||
using value_int = std::shared_ptr<value_int_t>;
|
||||
|
||||
|
||||
struct value_float_t : public value_t {
|
||||
static constexpr auto kind_id = value_kind::REAL;
|
||||
int64_t val_int;
|
||||
double val_flt;
|
||||
value_float_t(double v) : value_t(kind_id) {
|
||||
value val;
|
||||
value_float_t(double v) {
|
||||
val_flt = v;
|
||||
val_int = std::isfinite(v) ? float_to_int(v) : 0;
|
||||
val_int = std::isfinite(v) ? static_cast<int64_t>(v) : 0;
|
||||
val = mk_val<value_int>(val_int);
|
||||
}
|
||||
virtual std::string type() const override { return "Float"; }
|
||||
virtual double as_float() const override { return val_flt; }
|
||||
@@ -313,7 +272,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<double>(val_int) == val_flt) {
|
||||
return value_int_t(val_int).unique_hash();
|
||||
return val->unique_hash();
|
||||
} else {
|
||||
return hasher(typeid(*this))
|
||||
.update(&val_int, sizeof(val_int))
|
||||
@@ -322,22 +281,19 @@ struct value_float_t : public value_t {
|
||||
}
|
||||
protected:
|
||||
virtual bool equivalent(const value_t & other) const override {
|
||||
return other.is_numeric() && val_int == other.as_int() && val_flt == other.as_float();
|
||||
return other.is_numeric() && val_int == other.val_int && val_flt == other.val_flt;
|
||||
}
|
||||
virtual bool nonequal(const value_t & other) const override {
|
||||
return !(kind == other.kind && val_flt == other.as_float());
|
||||
return !(typeid(*this) == typeid(other) && val_flt == other.val_flt);
|
||||
}
|
||||
};
|
||||
using value_float = std::shared_ptr<value_float_t>;
|
||||
|
||||
|
||||
struct value_string_t : public value_t {
|
||||
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)) {}
|
||||
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; }
|
||||
virtual std::string type() const override { return "String"; }
|
||||
virtual string as_string() const override { return val_str; }
|
||||
virtual std::string as_repr() const override {
|
||||
@@ -348,7 +304,7 @@ struct value_string_t : public value_t {
|
||||
return ss.str();
|
||||
}
|
||||
virtual bool as_bool() const override {
|
||||
return !val_str.empty();
|
||||
return val_str.length() > 0;
|
||||
}
|
||||
virtual const func_builtins & get_builtins() const override;
|
||||
virtual bool is_hashable() const override { return true; }
|
||||
@@ -364,50 +320,51 @@ struct value_string_t : public value_t {
|
||||
}
|
||||
protected:
|
||||
virtual bool equivalent(const value_t & other) const override {
|
||||
return kind == other.kind && val_str.equals(static_cast<const value_string_t &>(other).val_str);
|
||||
return typeid(*this) == typeid(other) && val_str.str() == other.val_str.str();
|
||||
}
|
||||
};
|
||||
using value_string = std::shared_ptr<value_string_t>;
|
||||
|
||||
|
||||
struct value_bool_t : public value_t {
|
||||
static constexpr auto kind_id = value_kind::BOOLEAN;
|
||||
int64_t val_int;
|
||||
double val_flt;
|
||||
value_bool_t(bool v) : value_t(kind_id) {
|
||||
value val;
|
||||
value_bool_t(bool v) {
|
||||
val_int = static_cast<int64_t>(v);
|
||||
val_flt = static_cast<double>(v);
|
||||
val = mk_val<value_int>(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 value_int_t(val_int).unique_hash();
|
||||
return val->unique_hash();
|
||||
}
|
||||
protected:
|
||||
virtual bool equivalent(const value_t & other) const override {
|
||||
return other.is_numeric() && val_int == other.as_int() && val_flt == other.as_float();
|
||||
return other.is_numeric() && val_int == other.val_int && val_flt == other.val_flt;
|
||||
}
|
||||
virtual bool nonequal(const value_t & other) const override {
|
||||
return !(kind == other.kind && val_int == other.as_int());
|
||||
return !(typeid(*this) == typeid(other) && val_int == other.val_int);
|
||||
}
|
||||
};
|
||||
using value_bool = std::shared_ptr<value_bool_t>;
|
||||
|
||||
|
||||
struct value_array_t : public value_t {
|
||||
static constexpr auto kind_id = value_kind::ARRAY;
|
||||
std::vector<value> 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<value> && arr) : value_t(kind_id), val_arr(std::move(arr)) {}
|
||||
value_array_t(const std::vector<value> & arr) : value_t(kind_id), val_arr(arr) {}
|
||||
value_array_t() = default;
|
||||
value_array_t(value & v) {
|
||||
val_arr = v->val_arr;
|
||||
}
|
||||
value_array_t(std::vector<value> && arr) {
|
||||
val_arr = arr;
|
||||
}
|
||||
value_array_t(const std::vector<value> & arr) {
|
||||
val_arr = arr;
|
||||
}
|
||||
void reverse() {
|
||||
if (is_immutable()) {
|
||||
throw std::runtime_error("Attempting to modify immutable type");
|
||||
@@ -505,27 +462,24 @@ 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 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());
|
||||
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());
|
||||
}
|
||||
};
|
||||
using value_array = std::shared_ptr<value_array_t>;
|
||||
|
||||
|
||||
struct value_tuple_t : public value_array_t {
|
||||
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(value & v) {
|
||||
val_arr = v->val_arr;
|
||||
}
|
||||
value_tuple_t(std::vector<value> && arr) : value_array_t(kind_id) {
|
||||
val_arr = std::move(arr);
|
||||
}
|
||||
value_tuple_t(const std::vector<value> & arr) : value_array_t(kind_id) {
|
||||
value_tuple_t(std::vector<value> && arr) {
|
||||
val_arr = arr;
|
||||
}
|
||||
value_tuple_t(const std::pair<value, value> & pair) : value_array_t(kind_id) {
|
||||
value_tuple_t(const std::vector<value> & arr) {
|
||||
val_arr = arr;
|
||||
}
|
||||
value_tuple_t(const std::pair<value, value> & pair) {
|
||||
val_arr.push_back(pair.first);
|
||||
val_arr.push_back(pair.second);
|
||||
}
|
||||
@@ -536,23 +490,21 @@ using value_tuple = std::shared_ptr<value_tuple_t>;
|
||||
|
||||
|
||||
struct value_object_t : public value_t {
|
||||
static constexpr auto kind_id = value_kind::OBJECT;
|
||||
std::vector<std::pair<value, value>> val_obj;
|
||||
std::unordered_map<value, size_t, value_hasher, value_equivalence> key_index; // key -> index in val_obj
|
||||
std::unordered_map<value, value, value_hasher, value_equivalence> unordered;
|
||||
bool has_builtins = true; // context and loop objects do not have builtins
|
||||
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() = 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(const std::map<value, value> & obj) : value_t(kind_id) {
|
||||
value_object_t(const std::map<value, value> & obj) {
|
||||
for (const auto & pair : obj) {
|
||||
insert(pair.first, pair.second);
|
||||
}
|
||||
}
|
||||
value_object_t(const std::vector<std::pair<value, value>> & obj) : value_t(kind_id) {
|
||||
value_object_t(const std::vector<std::pair<value, value>> & obj) {
|
||||
for (const auto & pair : obj) {
|
||||
insert(pair.first, pair.second);
|
||||
}
|
||||
@@ -575,40 +527,45 @@ struct value_object_t : public value_t {
|
||||
return ss.str();
|
||||
}
|
||||
virtual bool as_bool() const override {
|
||||
return !val_obj.empty();
|
||||
return !unordered.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 key_index.find(key) != key_index.end();
|
||||
return unordered.find(key) != unordered.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 (!key->is_immutable() || !key->is_hashable()) {
|
||||
throw std::runtime_error("Object key of unhashable type: " + key->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;
|
||||
}
|
||||
}
|
||||
}
|
||||
const auto entry = key_index.try_emplace(key, val_obj.size());
|
||||
if (entry.second) {
|
||||
unordered[key] = val;
|
||||
if (!replaced) {
|
||||
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 (!key->is_immutable() || !key->is_hashable()) {
|
||||
throw std::runtime_error("Object key of unhashable type: " + key->type());
|
||||
if (!has_key(key)) {
|
||||
return default_val;
|
||||
}
|
||||
const auto found = key_index.find(key);
|
||||
return found == key_index.end() ? default_val : val_obj[found->second].second;
|
||||
return unordered.at(key);
|
||||
}
|
||||
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 val_obj[key_index.at(key)].second;
|
||||
return unordered.at(key);
|
||||
}
|
||||
virtual value & at(const std::string & key, value & default_val) override {
|
||||
value key_val = mk_val<value_string>(key);
|
||||
@@ -642,7 +599,7 @@ struct value_object_t : public value_t {
|
||||
}
|
||||
protected:
|
||||
virtual bool equivalent(const value_t & other) const override {
|
||||
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());
|
||||
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());
|
||||
}
|
||||
};
|
||||
using value_object = std::shared_ptr<value_object_t>;
|
||||
@@ -652,8 +609,6 @@ using value_object = std::shared_ptr<value_object_t>;
|
||||
//
|
||||
|
||||
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; }
|
||||
@@ -666,15 +621,14 @@ struct value_none_t : public value_t {
|
||||
}
|
||||
protected:
|
||||
virtual bool equivalent(const value_t & other) const override {
|
||||
return kind == other.kind;
|
||||
return typeid(*this) == typeid(other);
|
||||
}
|
||||
};
|
||||
using value_none = std::shared_ptr<value_none_t>;
|
||||
|
||||
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 = "") : value_t(kind_id), hint(h) {}
|
||||
value_undefined_t(const std::string & h = "") : 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; }
|
||||
@@ -751,14 +705,12 @@ private:
|
||||
};
|
||||
|
||||
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) : value_t(kind_id), name(name) {
|
||||
value_func_t(const std::string & name, const func_handler & func) : name(name) {
|
||||
val_func = func;
|
||||
}
|
||||
value_func_t(const std::string & name, const func_handler & func, const value & arg_this) : value_t(kind_id), name(name), arg0(arg_this) {
|
||||
value_func_t(const std::string & name, const func_handler & func, const value & arg_this) : name(name), arg0(arg_this) {
|
||||
val_func = func;
|
||||
}
|
||||
virtual value invoke(const func_args & args) const override {
|
||||
@@ -783,22 +735,18 @@ protected:
|
||||
// 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<func_hptr>();
|
||||
const auto target_other = static_cast<const value_func_t &>(other).val_func.target<func_hptr>();
|
||||
return target_this == target_other;
|
||||
const auto target_other = other.val_func.target<func_hptr>();
|
||||
return typeid(*this) == typeid(other) && target_this == target_other;
|
||||
}
|
||||
};
|
||||
using value_func = std::shared_ptr<value_func_t>;
|
||||
|
||||
// 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) : value_t(kind_id), key(k), val(v) {}
|
||||
value_kwarg_t(const std::string & k, const value & v) : 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; }
|
||||
@@ -812,7 +760,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<const value_kwarg_t &>(other);
|
||||
return kind == other.kind && key == other_val.key && val == other_val.val;
|
||||
return typeid(*this) == typeid(other) && key == other_val.key && val == other_val.val;
|
||||
}
|
||||
};
|
||||
using value_kwarg = std::shared_ptr<value_kwarg_t>;
|
||||
|
||||
@@ -676,8 +676,8 @@ private:
|
||||
const auto & node = trie.nodes[idx];
|
||||
std::string rejects;
|
||||
auto first = true;
|
||||
for (const auto & [sym, child] : node.children) {
|
||||
std::string c = common_unicode_cpt_to_utf8(sym.value);
|
||||
for (const auto & [cpt, child] : node.children) {
|
||||
std::string c = common_unicode_cpt_to_utf8(cpt);
|
||||
rejects += c;
|
||||
if (first) {
|
||||
first = false;
|
||||
|
||||
+26
-31
@@ -24,9 +24,7 @@ struct depth_guard {
|
||||
// Gemma 4 value parsers
|
||||
void gemma4_value_rules(common_chat_peg_builder & p) {
|
||||
// The tags are what gemma4_to_json() in the mapper reads, the rules may wrap them freely.
|
||||
auto string_delim = p.token("<|\"|>");
|
||||
|
||||
p.rule("gemma4-string", p.tag(gemma4::STRING, string_delim + p.tag(gemma4::STRING_CONTENT, p.until(string_delim)) + string_delim));
|
||||
p.rule("gemma4-string", p.tag(gemma4::STRING, p.literal("<|\"|>") + p.tag(gemma4::STRING_CONTENT, p.until("<|\"|>")) + p.literal("<|\"|>")));
|
||||
|
||||
p.rule("gemma4-bool", p.tag(gemma4::BOOL, p.json_bool()));
|
||||
|
||||
@@ -36,7 +34,7 @@ void gemma4_value_rules(common_chat_peg_builder & p) {
|
||||
|
||||
// Keys are bare in the template, but Gemma 4 occasionally wraps them in quotes
|
||||
p.rule("gemma4-dict-key", p.tag(gemma4::DICT_KEY, p.choice({
|
||||
string_delim + p.tag(gemma4::DICT_KEY_NAME, p.until(string_delim)) + string_delim,
|
||||
p.literal("<|\"|>") + p.tag(gemma4::DICT_KEY_NAME, p.until("<|\"|>")) + p.literal("<|\"|>"),
|
||||
p.literal("\"") + p.tag(gemma4::DICT_KEY_NAME, p.chars("[^\"]", 1, -1)) + p.literal("\""),
|
||||
p.literal("'") + p.tag(gemma4::DICT_KEY_NAME, p.chars("[^']", 1, -1)) + p.literal("'"),
|
||||
p.tag(gemma4::DICT_KEY_NAME, p.chars("[^:}]", 1, -1)),
|
||||
@@ -146,7 +144,7 @@ class gemma4_schema_parser {
|
||||
alts |= name();
|
||||
}
|
||||
// Gemma 4 may emit keys in its string delimiters or quotes
|
||||
alts |= p_.token("<|\"|>") + name() + p_.token("<|\"|>");
|
||||
alts |= p_.literal("<|\"|>") + name() + p_.literal("<|\"|>");
|
||||
if (key.find('\'') == std::string::npos) {
|
||||
alts |= p_.literal("'") + name() + p_.literal("'");
|
||||
}
|
||||
@@ -305,8 +303,7 @@ 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";
|
||||
// a tool call may start before the thought channel is closed; <channel|> stays first, the budget sampler forces it
|
||||
data.thinking_end_tags = {"<channel|>", "<|tool_call>"};
|
||||
data.thinking_end_tags = {"<channel|>"};
|
||||
|
||||
data.preserved_tokens = {
|
||||
"<|channel>",
|
||||
@@ -333,23 +330,17 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template &
|
||||
auto include_grammar = has_response_format || (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(inputs.specials, [&](common_chat_peg_builder & p) {
|
||||
auto start = p.rule("start", p.optional(p.token("<|turn>") + p.literal("model\n")));
|
||||
auto channel_start = p.token("<|channel>");
|
||||
auto channel_end = p.token("<channel|>");
|
||||
auto think_start = channel_start + p.literal("thought");
|
||||
auto tool_call_start = p.token("<|tool_call>");
|
||||
// the model may start a tool call before closing the thought channel
|
||||
auto think_end = channel_end | p.peek(tool_call_start);
|
||||
data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
||||
auto start = p.rule("start", p.optional(p.literal("<|turn>model\n")));
|
||||
|
||||
if (extract_reasoning) {
|
||||
p.rule("thought", think_start + p.space() + p.reasoning(p.until(channel_end | tool_call_start)) + think_end);
|
||||
p.rule("thought", p.literal("<|channel>thought") + p.space() + p.reasoning(p.until("<channel|>")) + p.literal("<channel|>"));
|
||||
} else {
|
||||
p.rule("thought", p.content(think_start + p.space() + p.until(channel_end | tool_call_start) + think_end));
|
||||
p.rule("thought", p.content(p.literal("<|channel>thought") + p.space() + p.until("<channel|>") + p.literal("<channel|>")));
|
||||
}
|
||||
|
||||
auto consume_empty_channels = p.gbnf(p.zero_or_more(channel_start + p.negate(p.literal("thought"))), "");
|
||||
auto thought = (p.peek(channel_start) + consume_empty_channels + p.ref("thought")) | p.negate(channel_start);
|
||||
auto consume_empty_channels = p.gbnf(p.zero_or_more(p.literal("<|channel>") + p.negate(p.literal("thought"))), "");
|
||||
auto thought = (p.peek(p.literal("<|channel>")) + consume_empty_channels + p.ref("thought")) | p.negate(p.literal("<|channel>"));
|
||||
|
||||
if (has_response_format) {
|
||||
auto response_format = p.literal("```json") <<
|
||||
@@ -385,35 +376,39 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template &
|
||||
})));
|
||||
});
|
||||
|
||||
auto tool_call_rest = p.literal("call:") + tool_choice + p.token("<tool_call|>");
|
||||
auto tool_call = p.rule("tool-call", tool_call_start + tool_call_rest);
|
||||
auto more = inputs.parallel_tool_calls ? p.zero_or_more(tool_call) : p.eps();
|
||||
|
||||
auto tool_calls = p.trigger_rule("tool-calls", tool_call_start, tool_call_rest + more);
|
||||
auto tool_call = p.trigger_rule("tool-call", p.repeat(
|
||||
"<|tool_call>call:" + tool_choice + "<tool_call|>",
|
||||
/* min = */ inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0,
|
||||
/* max = */ inputs.parallel_tool_calls ? -1 : 1
|
||||
));
|
||||
|
||||
if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
|
||||
return start + thought + tool_calls;
|
||||
return start + thought + tool_call;
|
||||
}
|
||||
|
||||
auto scan_to_toolcall = p.rule("scan-to-toolcall", p.until(tool_call_start));
|
||||
auto content = p.rule("content", p.content(p.until(channel_start | channel_end | tool_call_start)));
|
||||
auto scan_to_toolcall = p.rule("scan-to-toolcall", p.until("<|tool_call>"));
|
||||
auto content = p.rule("content", p.content(p.until_one_of({"<|channel>", "<channel|>", "<|tool_call>"})));
|
||||
auto message = p.rule("message", thought + content);
|
||||
return start + p.zero_or_more(message) + scan_to_toolcall + p.optional(tool_calls);
|
||||
return start + p.zero_or_more(message) + scan_to_toolcall + tool_call;
|
||||
}
|
||||
|
||||
// Gemma 4 may emit an extra <|channel>thought\n<channel|> at the end of the content. It may
|
||||
// also emit a single trailing <channel|> token. Consume all complete reasoning blocks and
|
||||
// then stop at the first unmatched <channel|> token.
|
||||
auto content = p.rule("content", p.content(p.until(channel_start | channel_end)));
|
||||
auto content = p.rule("content", p.content(p.until_one_of({"<|channel>", "<channel|>"})));
|
||||
auto message = p.rule("message", thought + content);
|
||||
return start + p.one_or_more(message);
|
||||
});
|
||||
|
||||
if (include_grammar) {
|
||||
data.grammar_lazy = false;
|
||||
data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED));
|
||||
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
|
||||
data.parser.build_grammar(builder, !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED)));
|
||||
data.parser.build_grammar(builder, data.grammar_lazy);
|
||||
});
|
||||
|
||||
data.grammar_triggers = {
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<|tool_call>" },
|
||||
};
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
+30
-31
@@ -65,18 +65,17 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template &
|
||||
auto include_grammar = has_response_format || (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(inputs.specials, [&](common_chat_peg_builder & p) {
|
||||
auto start_assistant = p.token("<|start|>") + p.literal("assistant");
|
||||
auto start = p.rule("start", start_assistant);
|
||||
auto end = p.rule("end", p.token("<|end|>"));
|
||||
auto content = p.rule("message-content", p.until(p.token("<|end|>")));
|
||||
auto channel = p.token("<|channel|>") + (p.literal("commentary") | p.literal("analysis"));
|
||||
data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
||||
auto start = p.rule("start", p.literal("<|start|>assistant"));
|
||||
auto end = p.rule("end", p.literal("<|end|>"));
|
||||
auto content = p.rule("message-content", p.until("<|end|>"));
|
||||
auto channel = p.literal("<|channel|>") + (p.literal("commentary") | p.literal("analysis"));
|
||||
auto constrain_type = p.chars("[A-Za-z0-9_-]", 1, -1);
|
||||
auto constraint = p.optional(p.chars("[ ]", 1, -1) + p.optional(p.token("<|constrain|>")) + constrain_type);
|
||||
auto constraint = p.optional(p.space() + p.optional(p.literal("<|constrain|>")) + constrain_type);
|
||||
|
||||
// Occasionally, gpt-oss-20b will prefix channels with this commentary
|
||||
auto stray_commentary = p.optional(p.token("<|channel|>") + p.literal("commentary") + p.optional(p.literal(" to=assistant")));
|
||||
auto start_analysis = stray_commentary + p.token("<|channel|>") + p.literal("analysis") + p.token("<|message|>");
|
||||
auto stray_commentary = p.optional(p.literal("<|channel|>commentary") + p.optional(p.literal(" to=assistant")));
|
||||
auto start_analysis = stray_commentary + p.literal("<|channel|>analysis<|message|>");
|
||||
|
||||
if (extract_reasoning) {
|
||||
p.rule("analysis", start_analysis + p.reasoning(content) + end);
|
||||
@@ -85,8 +84,8 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template &
|
||||
}
|
||||
|
||||
auto analysis = p.ref("analysis");
|
||||
auto preamble = p.rule("preamble", p.token("<|channel|>") + p.literal("commentary") + p.token("<|message|>") + p.content(content) + end);
|
||||
auto final_msg = p.rule("final", stray_commentary + p.token("<|channel|>") + p.literal("final") + constraint + p.token("<|message|>") + p.content(content));
|
||||
auto preamble = p.rule("preamble", p.literal("<|channel|>commentary<|message|>") + p.content(content) + end);
|
||||
auto final_msg = p.rule("final", stray_commentary + p.literal("<|channel|>final") + constraint + p.literal("<|message|>") + p.content(content));
|
||||
|
||||
// Consume any unsolicited tool calls, e.g. builtin functions
|
||||
auto unsolicited = p.rule("unsolicited", p.atomic(p.optional(channel) + p.literal(" to=") + content + end));
|
||||
@@ -95,58 +94,58 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template &
|
||||
|
||||
if (has_response_format) {
|
||||
auto response_format = p.rule("response-format",
|
||||
p.token("<|channel|>") + p.literal("final") + constraint + p.token("<|message|>") +
|
||||
p.literal("<|channel|>final") + constraint + p.literal("<|message|>") +
|
||||
p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)));
|
||||
|
||||
return p.zero_or_more(start + analysis) + start + response_format;
|
||||
}
|
||||
|
||||
if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
|
||||
auto in_role = p.choice();
|
||||
auto in_channel = p.choice();
|
||||
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");
|
||||
const auto params = common_chat_tool_parameters(function);
|
||||
|
||||
auto func_name = p.tool_name(p.literal(name));
|
||||
auto func_name = p.literal(" to=functions.") + p.tool_name(p.literal(name));
|
||||
auto args = p.tool_args(p.schema(p.json(), "tool-" + std::to_string(tool_index) + "-schema", params));
|
||||
|
||||
// recipient in role header
|
||||
// <|start|>assistant to=functions.NAME<|channel|>(commentary|analysis)[constraint]<|message|>ARGS
|
||||
in_role |= p.rule("tool-" + std::to_string(tool_index) + "-in-role",
|
||||
p.atomic(func_name + channel + constraint + p.token("<|message|>")) + args);
|
||||
auto tool_in_role = p.tool(p.tool_open(func_name + channel + constraint + p.literal("<|message|>")) + args);
|
||||
|
||||
// recipient in channel header
|
||||
// <|start|>assistant<|channel|>(commentary|analysis) to=functions.NAME[constraint]<|message|>ARGS
|
||||
in_channel |= p.rule("tool-" + std::to_string(tool_index) + "-in-channel",
|
||||
p.atomic(func_name + constraint + p.token("<|message|>")) + args);
|
||||
// <|channel|>(commentary|analysis) to=functions.NAME[constraint]<|message|>ARGS
|
||||
auto tool_in_channel = p.tool(p.tool_open(channel + func_name + constraint + p.literal("<|message|>")) + args);
|
||||
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), tool_in_role | tool_in_channel);
|
||||
});
|
||||
|
||||
// The recipient prefix is the trigger, so the grammar constrains the name that follows it
|
||||
auto to_functions = p.tool_open(p.literal(" to=functions."));
|
||||
auto tool_call = p.choice({
|
||||
p.trigger_rule("tool-call-in-role", start_assistant + to_functions, in_role),
|
||||
p.trigger_rule("tool-call-in-channel", start_assistant + channel + to_functions, in_channel)
|
||||
});
|
||||
auto tool_call = p.trigger_rule("tool-call", tool_choice);
|
||||
|
||||
if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
|
||||
return p.zero_or_more(start + any) + tool_call;
|
||||
return p.zero_or_more(start + any) + start + tool_call;
|
||||
}
|
||||
|
||||
return p.zero_or_more(start + any) + (tool_call | (start + final_msg));
|
||||
return p.zero_or_more(start + any) + start + (tool_call | final_msg);
|
||||
}
|
||||
|
||||
return p.zero_or_more(start + any) + start + (final_msg | unsolicited);
|
||||
});
|
||||
|
||||
if (include_grammar) {
|
||||
// The grammar scans for the triggers itself, so the sampler runs it from the first token
|
||||
data.grammar_lazy = false;
|
||||
data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED));
|
||||
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
|
||||
data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO);
|
||||
data.parser.build_grammar(builder, data.grammar_lazy);
|
||||
});
|
||||
|
||||
data.grammar_triggers = {
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "^\\s+to$" },
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "^<\\|channel\\|>(?:commentary|analysis)\\s+to=functions$" },
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|start\\|>assistant(\\s+to)" },
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|start\\|>assistant(<\\|channel\\|>(?:commentary|analysis)\\s+to)" }
|
||||
};
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
@@ -99,11 +99,8 @@ common_chat_params common_chat_params_init_harmony_xml(const common_chat_templat
|
||||
auto arg_close = p.tool_arg_close(p.gbnf(
|
||||
p.literal(PARAM_CLOSE) | (p.literal("\n") + p.peek(p.optional(p.literal("\n")) + next_open)),
|
||||
gbnf_format_literal("\n") + " " + gbnf_format_literal(PARAM_CLOSE.substr(1)) + "?"));
|
||||
auto string_value = p.tool_arg_string_value(p.until_one_of(string_ends));
|
||||
auto arg_string = p.rule("rfl-arg-string", p.through(string_value, p.tool_arg_close(p.literal(PARAM_CLOSE))));
|
||||
// the parser also accepts a value with no closing tag, the grammar still requires the closing tag
|
||||
auto missing_close = string_value + p.tool_arg_close(p.literal("\n") + p.peek(p.optional(p.literal("\n")) + next_open));
|
||||
arg_string = p.gbnf(arg_string | missing_close, "rfl-arg-string");
|
||||
auto arg_string = p.rule("rfl-arg-string",
|
||||
p.ac(p.tool_arg_string_value(p.until_one_of(string_ends)) + arg_close, PARAM_CLOSE));
|
||||
auto arg_sep = p.optional(p.literal("\n"));
|
||||
|
||||
std::string call_close_gbnf = gbnf_format_literal("<|end|>");
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
#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
|
||||
// <header><|content_text|>{media}text<|end_message|> --> <header>{media}<|end_message|><header><|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<common_chat_prompt_part> 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;
|
||||
}
|
||||
@@ -91,7 +91,7 @@ common_chat_params common_chat_params_init_k2_horizon(const common_chat_template
|
||||
}
|
||||
auto think_body = p.until_one_of(data.thinking_end_tags);
|
||||
auto think_block = [&](const common_peg_parser & body) {
|
||||
return p.optional(THINK_START + p.space() + p.through(body, think_end));
|
||||
return p.optional(THINK_START + p.space() + p.ac(body + think_end, data.thinking_end_tags));
|
||||
};
|
||||
auto reasoning = extract_reasoning ? think_block(p.reasoning(think_body)) : p.eps();
|
||||
|
||||
@@ -110,7 +110,7 @@ common_chat_params common_chat_params_init_k2_horizon(const common_chat_template
|
||||
tool_choice = p.standard_json_tools(CALL_START, CALL_END, inputs.tools, false, true);
|
||||
} else {
|
||||
auto arg_close = p.tool_arg_close(p.literal(ARG_VAL_END));
|
||||
auto arg_string = p.rule("xml-arg-string", p.through(p.tool_arg_string_value(p.until(ARG_VAL_END)), arg_close));
|
||||
auto arg_string = p.rule("xml-arg-string", p.ac(p.tool_arg_string_value(p.until(ARG_VAL_END)) + arg_close, ARG_VAL_END));
|
||||
|
||||
// The models leave out <ifm|arg_type> even when asked for xml_typed
|
||||
auto arg_type = call_format == "xml_typed" ? p.optional(ARG_TYPE + p.until(ARG_TYPE_END) + ARG_TYPE_END + p.space()) : p.eps();
|
||||
|
||||
@@ -83,8 +83,7 @@ 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,
|
||||
/* allow_undeclared = */ true) +
|
||||
p.python_style_tool_calls(inputs.tools, inputs.parallel_tool_calls, /* allow_json_literals = */ true) +
|
||||
p.literal(TOOL_CALL_END)
|
||||
)
|
||||
);
|
||||
|
||||
@@ -63,8 +63,8 @@ common_chat_params common_chat_params_init_minicpm5(const common_chat_template &
|
||||
// CDATA lets a value carry characters that would otherwise close the tag (e.g.
|
||||
// </param>); capture the inner text only, excluding the CDATA markers.
|
||||
auto string_value = p.choice({
|
||||
p.literal("<![CDATA[") + p.through(p.tool_arg_string_value(p.until("]]>")), "]]>") + p.tool_arg_close(p.literal("</param>")),
|
||||
p.negate(p.literal("<![CDATA[")) + p.through(p.tool_arg_string_value(p.until("</param>")), p.tool_arg_close(p.literal("</param>")))
|
||||
p.literal("<![CDATA[") + p.ac(p.tool_arg_string_value(p.until("]]>")) + p.literal("]]>"), "]]>") + p.tool_arg_close(p.literal("</param>")),
|
||||
p.negate(p.literal("<![CDATA[")) + p.ac(p.tool_arg_string_value(p.until("</param>")) + p.tool_arg_close(p.literal("</param>")), "</param>")
|
||||
});
|
||||
|
||||
auto tool_choice = p.choice();
|
||||
|
||||
@@ -64,8 +64,8 @@ common_chat_params common_chat_params_init_minimax_m3(const common_chat_template
|
||||
if (extract_reasoning) {
|
||||
auto block = inputs.enable_thinking
|
||||
? p.literal(THINK_START) + p.space() +
|
||||
p.through(p.reasoning(p.until(THINK_END)), THINK_END)
|
||||
: p.literal(THINK_START) + p.through(p.until(THINK_END), THINK_END);
|
||||
p.ac(p.reasoning(p.until(THINK_END)) + p.literal(THINK_END), THINK_END)
|
||||
: p.literal(THINK_START) + p.ac(p.until(THINK_END) + p.literal(THINK_END), THINK_END);
|
||||
|
||||
// A turn without reasoning is prefixed with a bare </mm:think>, written either by the
|
||||
// generation prompt (thinking_mode = "disabled") or by the model itself.
|
||||
@@ -113,7 +113,7 @@ common_chat_params common_chat_params_init_minimax_m3(const common_chat_template
|
||||
|
||||
// A string accepts anything, so a union with a string alternative is a string
|
||||
if (schema.may_be_string()) {
|
||||
return p.through(p.tool_arg_string_value(p.until(close)), close_tag);
|
||||
return p.ac(p.tool_arg_string_value(p.until(close)) + close_tag, close);
|
||||
}
|
||||
|
||||
if (schema.kind() == common_chat_schema::KIND_ANY_OF) {
|
||||
|
||||
@@ -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]", "[TOOL_CALLS]"};
|
||||
data.thinking_end_tags = {"[/THINK]"};
|
||||
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_one_of({"[/THINK]", "[TOOL_CALLS]"})) + p.choice({p.literal("[/THINK]"), p.peek(p.literal("[TOOL_CALLS]"))})) : p.eps();
|
||||
extract_reasoning ? p.optional("[THINK]" + p.reasoning(p.until("[/THINK]")) + "[/THINK]") : p.eps();
|
||||
|
||||
// Response format parser
|
||||
if (has_response_format) {
|
||||
|
||||
@@ -17,7 +17,7 @@ common_chat_params common_chat_params_init_muse_glimmer(const common_chat_templa
|
||||
data.supports_thinking = true;
|
||||
|
||||
data.preserved_tokens = {
|
||||
"<|start|>", "<|message|>", "<|eom|>",
|
||||
"<|start|>", "<|message|>", "<|eom|>", "<|eot|>",
|
||||
// ATEM tool-call markup emitted on " to=<tool>" turns.
|
||||
"<atem:function_calls>", "<atem:invoke", "<atem:parameter", "</atem:parameter>",
|
||||
"</atem:invoke>", "</atem:function_calls>",
|
||||
@@ -48,38 +48,37 @@ common_chat_params common_chat_params_init_muse_glimmer(const common_chat_templa
|
||||
// Constrained grammar whenever tools are offered or a response format is requested.
|
||||
auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE);
|
||||
|
||||
data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) {
|
||||
auto start_token = p.token("<|start|>");
|
||||
auto message = p.token("<|message|>");
|
||||
auto eom = p.token("<|eom|>");
|
||||
auto start = p.rule("start", start_token + p.literal("assistant"));
|
||||
data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
||||
auto start = p.rule("start", p.literal("<|start|>assistant"));
|
||||
|
||||
if (!extract_reasoning && !include_grammar) {
|
||||
return start + p.content(p.rest());
|
||||
}
|
||||
|
||||
if (extract_reasoning) {
|
||||
p.rule("analysis", p.literal(" to=self") + message + p.reasoning(p.until(eom)) + eom);
|
||||
p.rule("analysis", p.literal(" to=self<|message|>") + p.reasoning(p.until("<|eom|>")) + p.literal("<|eom|>"));
|
||||
} else {
|
||||
p.rule("analysis", p.literal(" to=self") + message + p.content(p.until(eom)) + eom);
|
||||
p.rule("analysis", p.literal(" to=self<|message|>") + p.content(p.until("<|eom|>")) + p.literal("<|eom|>"));
|
||||
}
|
||||
auto analysis = p.ref("analysis");
|
||||
|
||||
auto recipient = p.optional(p.literal(" to=user"));
|
||||
auto final_msg = p.rule("final", recipient + message + p.content(p.until(eom)));
|
||||
auto final_msg = p.rule("final", recipient + p.literal("<|message|>") +
|
||||
p.content(p.until_one_of({ "<|eot|>", "<|eom|>" })));
|
||||
|
||||
if (has_response_format) {
|
||||
auto response_json = p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema));
|
||||
auto response_format = p.rule("response-format",
|
||||
recipient + message +
|
||||
recipient + p.literal("<|message|>") +
|
||||
((p.literal("```json") + p.space() + response_json + p.space() + p.literal("```")) | response_json));
|
||||
|
||||
return p.zero_or_more(start + analysis) + start + response_format;
|
||||
}
|
||||
|
||||
if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
|
||||
auto string_value = p.through(p.tool_arg_string_value(p.until("</atem:parameter>")),
|
||||
p.tool_arg_close(p.literal("</atem:parameter>")));
|
||||
auto string_value = p.ac(
|
||||
p.tool_arg_string_value(p.until("</atem:parameter>")) + p.tool_arg_close(p.literal("</atem:parameter>")),
|
||||
"</atem:parameter>");
|
||||
|
||||
auto tool_choice = p.choice();
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
@@ -107,35 +106,40 @@ common_chat_params common_chat_params_init_muse_glimmer(const common_chat_templa
|
||||
args = p.zero_or_more(p.choice(arg_rules) + p.space());
|
||||
}
|
||||
|
||||
auto open = p.tool_open(start_token + p.literal("assistant to=") + p.tool_name(p.literal(name)) + message);
|
||||
auto body = p.rule("tool-" + std::to_string(tool_index),
|
||||
p.literal("<atem:function_calls>") + p.space() + p.literal("<atem:invoke name=\"" + name + "\">") + p.space()
|
||||
auto tool_parser = p.tool(
|
||||
p.tool_open(p.literal(" to=") + p.until("<|message|>") +
|
||||
p.literal("<|message|><atem:function_calls>") + p.space() +
|
||||
p.literal("<atem:invoke name=\"") + p.tool_name(p.literal(name)) + p.literal("\">") + p.space())
|
||||
<< p.tool_args(args)
|
||||
<< p.tool_close(p.literal("</atem:invoke>") + p.space() + p.literal("</atem:function_calls>")));
|
||||
|
||||
tool_choice |= open + body;
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), tool_parser);
|
||||
});
|
||||
|
||||
auto more = inputs.parallel_tool_calls ? p.zero_or_more(eom + tool_choice) : p.eps();
|
||||
auto tool_calls = p.rule("tool-calls", tool_choice + more);
|
||||
auto tool_calls = inputs.parallel_tool_calls
|
||||
? p.trigger_rule("tool-call", tool_choice + p.zero_or_more(p.literal("<|eom|>") + start + tool_choice))
|
||||
: p.trigger_rule("tool-call", tool_choice);
|
||||
|
||||
|
||||
if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
|
||||
return p.zero_or_more(start + analysis) + tool_calls;
|
||||
return p.zero_or_more(start + analysis) + start + tool_calls;
|
||||
}
|
||||
auto trailing_calls = p.optional(eom + tool_calls);
|
||||
return p.zero_or_more(start + analysis) + (tool_calls | (start + final_msg + trailing_calls));
|
||||
auto trailing_calls = p.optional(p.literal("<|eom|>") + start + tool_calls);
|
||||
return p.zero_or_more(start + analysis) + start + (tool_calls | (final_msg + trailing_calls));
|
||||
}
|
||||
|
||||
return p.zero_or_more(start + analysis) + start + final_msg;
|
||||
});
|
||||
|
||||
if (include_grammar) {
|
||||
// Every message starts with a recipient header, so the grammar is not lazy.
|
||||
// The model cannot generate a recipient that is not self, user, or a tool.
|
||||
data.grammar_lazy = false;
|
||||
data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED));
|
||||
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
|
||||
data.parser.build_grammar(builder);
|
||||
data.parser.build_grammar(builder, data.grammar_lazy);
|
||||
});
|
||||
data.grammar_triggers = {
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN,
|
||||
"(?:^|<\\|start\\|>assistant)( to=(?!self<\\|message\\|>)(?!user<\\|message\\|>)[^<]*?<\\|message\\|>)" },
|
||||
};
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
@@ -86,8 +86,9 @@ common_chat_params common_chat_params_init_muse_spark(const common_chat_template
|
||||
}
|
||||
|
||||
if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
|
||||
auto string_value = p.through(p.tool_arg_string_value(p.until("</atem:parameter>")),
|
||||
p.tool_arg_close(p.literal("</atem:parameter>")));
|
||||
auto string_value = p.ac(
|
||||
p.tool_arg_string_value(p.until("</atem:parameter>")) + p.tool_arg_close(p.literal("</atem:parameter>")),
|
||||
"</atem:parameter>");
|
||||
|
||||
auto tool_choice = p.choice();
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
|
||||
@@ -41,8 +41,6 @@ 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);
|
||||
@@ -57,8 +55,6 @@ 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);
|
||||
|
||||
@@ -59,16 +59,27 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat
|
||||
data.prompt.append(data.generation_prompt);
|
||||
}
|
||||
|
||||
data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) {
|
||||
std::vector<std::string> tool_call_starts = { "<tool_call>" };
|
||||
|
||||
if (is_qwen3_coder) {
|
||||
// Match complete <function=name> opener for Qwen3-Coder models that occasionally omit the
|
||||
// starting <tool_call>. The model may hallucinate a tool name, but it is preferable over
|
||||
// constraining on <function which may occur in valid content generation, e.g. #include <functional>
|
||||
foreach_function(inputs.tools, [&](size_t, const json & tool) {
|
||||
const std::string name = tool.at("function").at("name");
|
||||
tool_call_starts.push_back("<function=" + name + ">");
|
||||
});
|
||||
}
|
||||
|
||||
data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
||||
auto generation_prompt = p.literal(GEN_PREFIX);
|
||||
|
||||
// The template strips the newline before </think>, so leave it out of the reasoning
|
||||
auto think_end = (p.literal("\n") + p.token("</think>")) | p.token("</think>");
|
||||
auto think_body = p.until(think_end | p.token("<tool_call>"));
|
||||
auto think_close = think_end | p.peek(p.token("<tool_call>"));
|
||||
auto think_body = p.until_one_of({ "\n</think>", "</think>", "<tool_call>" });
|
||||
auto think_close = p.literal("\n</think>") | p.literal("</think>") | p.peek(p.literal("<tool_call>"));
|
||||
|
||||
auto reasoning_extracted = p.optional(p.token("<think>") + p.space() + p.reasoning(think_body) + think_close);
|
||||
auto reasoning_skipped = p.optional(p.token("<think>") + p.space() + think_body + think_close);
|
||||
auto reasoning_extracted = p.optional("<think>" + p.space() + p.reasoning(think_body) + think_close);
|
||||
auto reasoning_skipped = p.optional("<think>" + p.space() + think_body + think_close);
|
||||
|
||||
auto reasoning = p.eps();
|
||||
if (supports_reasoning && extract_reasoning) {
|
||||
@@ -88,13 +99,7 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat
|
||||
if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
|
||||
auto arg_close = p.tool_arg_close(p.literal("\n</parameter>\n"));
|
||||
auto arg_string = p.rule("xml-arg-string",
|
||||
p.through(p.tool_arg_string_value(p.until("\n</parameter>\n")), arg_close));
|
||||
|
||||
auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0;
|
||||
|
||||
auto more = inputs.parallel_tool_calls ? p.zero_or_more(p.ref("tool-call")) : p.eps();
|
||||
auto starts = p.token("<tool_call>");
|
||||
auto tool_calls = p.choice();
|
||||
p.ac(p.tool_arg_string_value(p.until("\n</parameter>\n")) + arg_close, "\n</parameter>\n"));
|
||||
|
||||
auto tool_choice = p.choice();
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
@@ -150,29 +155,35 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat
|
||||
args = args + p.zero_or_more(p.choice(optional_args));
|
||||
}
|
||||
|
||||
auto opener = p.tool_open("<function=" + p.tool_name(p.literal(name)) + ">");
|
||||
auto body = p.literal("\n") + p.tool_args(args) + p.tool_close(p.literal("</function>\n"));
|
||||
auto func = p.tool(p.tool_open("<function=" + p.tool_name(p.literal(name)) + ">\n") +
|
||||
p.tool_args(args) +
|
||||
p.tool_close(p.literal("</function>\n")));
|
||||
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(opener + body));
|
||||
|
||||
if (is_qwen3_coder) {
|
||||
// Qwen3-Coder models sometimes omit <tool_call>, so the full <function=name> opener is also a trigger.
|
||||
// Do not trigger on <function alone, it occurs in normal content, e.g. #include <functional>.
|
||||
tool_calls |= p.trigger_rule("tool-calls-" + std::to_string(tool_index), opener, body + p.token("</tool_call>") + p.space() + more);
|
||||
starts |= opener;
|
||||
}
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), func);
|
||||
});
|
||||
|
||||
auto tool_call_body = tool_choice + p.token("</tool_call>") + p.space();
|
||||
p.rule("tool-call", p.token("<tool_call>") + p.literal("\n") + tool_call_body);
|
||||
auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0;
|
||||
|
||||
tool_calls |= p.trigger_rule("tool-calls", p.token("<tool_call>"), p.literal("\n") + tool_call_body + more);
|
||||
auto tool_call_body = tool_choice + "</tool_call>" + p.space();
|
||||
auto tool_call = p.rule("tool-call", "<tool_call>\n" + tool_call_body);
|
||||
|
||||
// Qwen3-Coder models may occasionally omit the <tool_call> token.
|
||||
auto tool_call_first = is_qwen3_coder ?
|
||||
p.rule("tool-call-first", p.optional(p.literal("<tool_call>\n")) + tool_call_body) :
|
||||
tool_call;
|
||||
|
||||
auto calls = inputs.parallel_tool_calls ? tool_call_first + p.zero_or_more(tool_call) : tool_call_first;
|
||||
auto tool_calls = p.trigger_rule("tool-call-root", p.repeat(calls, min_calls, 1));
|
||||
|
||||
// The templates separate content from the tool calls with one or two newlines,
|
||||
// stop the content before them
|
||||
auto content_end = (p.literal("\n\n") + starts) | (p.literal("\n") + starts) | starts;
|
||||
std::vector<std::string> content_ends;
|
||||
for (const auto & start : tool_call_starts) {
|
||||
content_ends.insert(content_ends.end(), { "\n\n" + start, "\n" + start, start });
|
||||
}
|
||||
|
||||
return generation_prompt + (reasoning << p.content(p.until(content_end)) << p.repeat(tool_calls, min_calls, 1));
|
||||
return generation_prompt +
|
||||
(reasoning << p.content(p.until_one_of(content_ends)) << tool_calls);
|
||||
}
|
||||
|
||||
// Content only parser
|
||||
@@ -180,11 +191,17 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat
|
||||
});
|
||||
|
||||
if (include_grammar) {
|
||||
// The grammar scans for the triggers itself, so the sampler runs it from the first token
|
||||
data.grammar_lazy = false;
|
||||
data.grammar_lazy = !has_response_format && has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO;
|
||||
|
||||
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
|
||||
data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO);
|
||||
data.parser.build_grammar(builder, data.grammar_lazy);
|
||||
});
|
||||
|
||||
if (data.grammar_lazy) {
|
||||
for (const auto & start : tool_call_starts) {
|
||||
data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, start });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
@@ -10,7 +10,6 @@ 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
|
||||
|
||||
+117
-545
@@ -208,89 +208,6 @@ void common_peg_ast_arena::visit(const common_peg_parse_result & result, const c
|
||||
}
|
||||
}
|
||||
|
||||
common_peg_tokens::common_peg_tokens(const llama_vocab * vocab) {
|
||||
const llama_token n_tokens = llama_vocab_n_tokens(vocab);
|
||||
for (llama_token id = 0; id < n_tokens; ++id) {
|
||||
const auto attr = llama_vocab_get_attr(vocab, id);
|
||||
if (attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED)) {
|
||||
std::string text = llama_vocab_get_text(vocab, id);
|
||||
ids.emplace(text, id);
|
||||
tokens.emplace(id, common_peg_token{ std::move(text), attr });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
llama_token common_peg_tokens::token_id(const std::string & text) const {
|
||||
auto it = ids.find(text);
|
||||
return it != ids.end() ? it->second : LLAMA_TOKEN_NULL;
|
||||
}
|
||||
|
||||
// Insert every delimiter the parser matches into the trie, starting from each node in from. Returns the end nodes.
|
||||
// A choice adds the delimiters of each branch. A sequence joins every combination of its children.
|
||||
static std::set<size_t> insert_delimiter(common_trie & trie, const common_peg_arena & arena, common_peg_parser_id id,
|
||||
std::set<size_t> from = { 0 }) {
|
||||
return std::visit([&](const auto & p) -> std::set<size_t> {
|
||||
using T = std::decay_t<decltype(p)>;
|
||||
if constexpr (std::is_same_v<T, common_peg_tag_parser> || std::is_same_v<T, common_peg_atomic_parser>) {
|
||||
return insert_delimiter(trie, arena, p.child, std::move(from));
|
||||
} else if constexpr (std::is_same_v<T, common_peg_literal_parser>) {
|
||||
std::set<size_t> ends;
|
||||
for (size_t node : from) {
|
||||
size_t pos = 0;
|
||||
while (pos < p.literal.size()) {
|
||||
auto result = common_parse_utf8_codepoint(p.literal, pos);
|
||||
if (result.status != utf8_parse_result::SUCCESS) {
|
||||
break;
|
||||
}
|
||||
node = trie.extend(node, common_trie::symbol::codepoint(result.codepoint));
|
||||
pos += result.bytes_consumed;
|
||||
}
|
||||
ends.insert(node);
|
||||
}
|
||||
return ends;
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_parser>) {
|
||||
std::set<size_t> ends;
|
||||
for (size_t node : from) {
|
||||
ends.insert(trie.extend(node, common_trie::symbol::token(p.token)));
|
||||
}
|
||||
return ends;
|
||||
} else if constexpr (std::is_same_v<T, common_peg_choice_parser>) {
|
||||
std::set<size_t> ends;
|
||||
for (auto child : p.children) {
|
||||
ends.merge(insert_delimiter(trie, arena, child, from));
|
||||
}
|
||||
return ends;
|
||||
} else if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
|
||||
for (auto child : p.children) {
|
||||
from = insert_delimiter(trie, arena, child, std::move(from));
|
||||
}
|
||||
return from;
|
||||
} else {
|
||||
throw std::invalid_argument("a delimiter may only be a sequence of literals, tokens, and choices of them, possibly wrapped in tags and atomics");
|
||||
}
|
||||
}, arena.get(id));
|
||||
}
|
||||
|
||||
// Build the matcher of an until parser, each pattern valued by the branch it belongs to
|
||||
static common_trie build_until_matcher(const common_peg_arena & arena,
|
||||
const std::vector<common_peg_until_branch> & branches,
|
||||
bool include) {
|
||||
common_trie matcher;
|
||||
for (size_t b = 0; b < branches.size(); b++) {
|
||||
for (size_t end : insert_delimiter(matcher, arena, branches[b].delimiter)) {
|
||||
if (end == 0) {
|
||||
throw std::invalid_argument("delimiter must not match the empty string");
|
||||
}
|
||||
// nothing follows a delimiter without include, so the first branch to claim it wins
|
||||
auto owner = matcher.mark(end, (int32_t) b);
|
||||
if (owner != (int32_t) b && include) {
|
||||
throw std::invalid_argument("until branches " + std::to_string(owner) + " and " + std::to_string(b) + " must not share a delimiter");
|
||||
}
|
||||
}
|
||||
}
|
||||
return matcher;
|
||||
}
|
||||
|
||||
struct parser_executor;
|
||||
|
||||
common_peg_parser_id common_peg_arena::add_parser(common_peg_parser_variant parser) {
|
||||
@@ -381,49 +298,6 @@ struct parser_executor {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
|
||||
}
|
||||
|
||||
common_peg_parse_result operator()(const common_peg_token_parser & p) {
|
||||
if (start_pos >= ctx.input.size()) {
|
||||
if (!ctx.is_lenient()) {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
|
||||
}
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos);
|
||||
}
|
||||
|
||||
if (start_pos >= ctx.tokens.size() || ctx.tokens[start_pos] != p.token) {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
|
||||
}
|
||||
|
||||
// Skip the rest of the piece, up to the next token or the end of the input
|
||||
auto pos = start_pos + 1;
|
||||
while (pos < ctx.input.size() && ctx.tokens[pos] == LLAMA_TOKEN_NULL) {
|
||||
++pos;
|
||||
}
|
||||
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
|
||||
}
|
||||
|
||||
common_peg_parse_result operator()(const common_peg_token_not_parser & p) {
|
||||
if (start_pos >= ctx.input.size()) {
|
||||
if (!ctx.is_lenient()) {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
|
||||
}
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos);
|
||||
}
|
||||
|
||||
if (start_pos >= ctx.tokens.size() || ctx.tokens[start_pos] == LLAMA_TOKEN_NULL ||
|
||||
std::find(p.tokens.begin(), p.tokens.end(), ctx.tokens[start_pos]) != p.tokens.end()) {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos);
|
||||
}
|
||||
|
||||
// Skip the rest of the piece, up to the next token or the end of the input
|
||||
auto pos = start_pos + 1;
|
||||
while (pos < ctx.input.size() && ctx.tokens[pos] == LLAMA_TOKEN_NULL) {
|
||||
++pos;
|
||||
}
|
||||
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos);
|
||||
}
|
||||
|
||||
common_peg_parse_result operator()(const common_peg_sequence_parser & p) {
|
||||
if (ctx.is_debug()) {
|
||||
LOG_DBG("%sSEQ start at %zu '%s' (%zu children)\n", debug_indent().c_str(), start_pos,
|
||||
@@ -815,11 +689,7 @@ struct parser_executor {
|
||||
}
|
||||
|
||||
common_peg_parse_result operator()(const common_peg_until_parser & p) const {
|
||||
if (p.include) {
|
||||
return parse_through(p);
|
||||
}
|
||||
|
||||
const auto & matcher = p.matcher;
|
||||
common_trie matcher(p.delimiters);
|
||||
|
||||
// Scan input and check for delimiters
|
||||
size_t pos = start_pos;
|
||||
@@ -827,24 +697,24 @@ struct parser_executor {
|
||||
std::vector<common_peg_invalid_utf8> invalid_utf8;
|
||||
|
||||
while (pos < ctx.input.size()) {
|
||||
auto step = matcher.next(ctx.input, ctx.tokens, pos);
|
||||
auto utf8_result = common_parse_utf8_codepoint(ctx.input, pos);
|
||||
|
||||
if (step.status == utf8_parse_result::INCOMPLETE && ctx.is_lenient()) {
|
||||
if (utf8_result.status == utf8_parse_result::INCOMPLETE && ctx.is_lenient()) {
|
||||
// The rest of the sequence may still arrive, return what we have so far
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, last_valid_pos, {}, std::move(invalid_utf8));
|
||||
}
|
||||
|
||||
if (step.status != utf8_parse_result::SUCCESS) {
|
||||
if (utf8_result.status != utf8_parse_result::SUCCESS) {
|
||||
// Malformed UTF-8, or a sequence truncated by the end of a complete input.
|
||||
// A delimiter cannot start inside bytes that fail to decode, so consume them and move on
|
||||
invalid_utf8.push_back({pos, step.bytes_consumed});
|
||||
pos += step.bytes_consumed;
|
||||
invalid_utf8.push_back({pos, utf8_result.bytes_consumed});
|
||||
pos += utf8_result.bytes_consumed;
|
||||
last_valid_pos = pos;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if a delimiter starts at this position
|
||||
auto match = matcher.check_at(ctx.input, ctx.tokens, pos);
|
||||
auto match = matcher.check_at(ctx.input, pos);
|
||||
|
||||
if (match == common_trie::COMPLETE_MATCH) {
|
||||
// Found a complete delimiter, return everything before it
|
||||
@@ -857,7 +727,7 @@ struct parser_executor {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos, {}, std::move(invalid_utf8));
|
||||
}
|
||||
|
||||
pos += step.bytes_consumed;
|
||||
pos += utf8_result.bytes_consumed;
|
||||
last_valid_pos = pos;
|
||||
}
|
||||
|
||||
@@ -868,48 +738,6 @@ struct parser_executor {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, last_valid_pos, {}, std::move(invalid_utf8));
|
||||
}
|
||||
|
||||
// Parse content, then the first branch whose delimiter and rest follow it, like C (D1 R1 | D2 R2 | ...)
|
||||
common_peg_parse_result parse_through(const common_peg_until_parser & p) const {
|
||||
auto content = arena.parse(p.content, ctx, start_pos);
|
||||
if (content.fail() || content.need_more_input()) {
|
||||
return content;
|
||||
}
|
||||
|
||||
auto pos = content.end;
|
||||
for (const auto & branch : p.branches) {
|
||||
auto nodes = content.nodes;
|
||||
auto invalid_utf8 = content.invalid_utf8;
|
||||
auto end = pos;
|
||||
bool matched = true;
|
||||
|
||||
for (auto id : { branch.delimiter, branch.rest }) {
|
||||
if (id == COMMON_PEG_INVALID_PARSER_ID) {
|
||||
continue;
|
||||
}
|
||||
auto result = arena.parse(id, ctx, end);
|
||||
if (result.fail()) {
|
||||
matched = false;
|
||||
break;
|
||||
}
|
||||
nodes.insert(nodes.end(), result.nodes.begin(), result.nodes.end());
|
||||
invalid_utf8.insert(invalid_utf8.end(), result.invalid_utf8.begin(), result.invalid_utf8.end());
|
||||
end = result.end;
|
||||
if (result.need_more_input()) {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, end, std::move(nodes), std::move(invalid_utf8));
|
||||
}
|
||||
}
|
||||
if (matched) {
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, end, std::move(nodes), std::move(invalid_utf8));
|
||||
}
|
||||
}
|
||||
|
||||
if (p.optional && pos == ctx.input.size()) {
|
||||
auto type = ctx.is_lenient() ? COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT : COMMON_PEG_PARSE_RESULT_SUCCESS;
|
||||
return common_peg_parse_result(type, start_pos, pos, std::move(content.nodes), std::move(content.invalid_utf8));
|
||||
}
|
||||
return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos, pos);
|
||||
}
|
||||
|
||||
common_peg_parse_result operator()(const common_peg_schema_parser & p) {
|
||||
return arena.parse(p.child, ctx, start_pos);
|
||||
}
|
||||
@@ -995,6 +823,10 @@ struct parser_executor {
|
||||
common_peg_parse_result operator()(const common_peg_gbnf_parser & p) {
|
||||
return arena.parse(p.child, ctx, start_pos);
|
||||
}
|
||||
|
||||
common_peg_parse_result operator()(const common_peg_ac_parser & p) {
|
||||
return arena.parse(p.child, ctx, start_pos);
|
||||
}
|
||||
};
|
||||
|
||||
common_peg_parse_result common_peg_arena::parse(common_peg_parse_context & ctx, size_t start) const {
|
||||
@@ -1067,33 +899,19 @@ void common_peg_arena::resolve_refs() {
|
||||
std::is_same_v<T, common_peg_not_parser> ||
|
||||
std::is_same_v<T, common_peg_tag_parser> ||
|
||||
std::is_same_v<T, common_peg_atomic_parser> ||
|
||||
std::is_same_v<T, common_peg_gbnf_parser>) {
|
||||
std::is_same_v<T, common_peg_gbnf_parser> ||
|
||||
std::is_same_v<T, common_peg_ac_parser>) {
|
||||
p.child = resolve_ref(p.child);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_until_parser>) {
|
||||
if (p.content != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
p.content = resolve_ref(p.content);
|
||||
}
|
||||
for (auto & branch : p.branches) {
|
||||
branch.delimiter = resolve_ref(branch.delimiter);
|
||||
if (branch.rest != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
branch.rest = resolve_ref(branch.rest);
|
||||
}
|
||||
}
|
||||
} else if constexpr (std::is_same_v<T, common_peg_rule_parser>) {
|
||||
p.child = resolve_ref(p.child);
|
||||
if (p.start != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
p.start = resolve_ref(p.start);
|
||||
p.rest = resolve_ref(p.rest);
|
||||
}
|
||||
} else if constexpr (std::is_same_v<T, common_peg_schema_parser>) {
|
||||
p.child = resolve_ref(p.child);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_epsilon_parser> ||
|
||||
std::is_same_v<T, common_peg_start_parser> ||
|
||||
std::is_same_v<T, common_peg_end_parser> ||
|
||||
std::is_same_v<T, common_peg_ref_parser> ||
|
||||
std::is_same_v<T, common_peg_until_parser> ||
|
||||
std::is_same_v<T, common_peg_literal_parser> ||
|
||||
std::is_same_v<T, common_peg_token_parser> ||
|
||||
std::is_same_v<T, common_peg_token_not_parser> ||
|
||||
std::is_same_v<T, common_peg_string_parser> ||
|
||||
std::is_same_v<T, common_peg_chars_parser> ||
|
||||
std::is_same_v<T, common_peg_any_parser> ||
|
||||
@@ -1137,14 +955,6 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id
|
||||
return "End";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_literal_parser>) {
|
||||
return "Literal(" + p.literal + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_parser>) {
|
||||
return "Token(" + p.piece + ", " + std::to_string(p.token) + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_not_parser>) {
|
||||
std::vector<std::string> parts;
|
||||
for (auto token : p.tokens) {
|
||||
parts.push_back(std::to_string(token));
|
||||
}
|
||||
return "TokenNot(" + string_join(parts, ", ") + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
|
||||
std::vector<std::string> parts;
|
||||
for (const auto & child : p.children) {
|
||||
@@ -1171,6 +981,8 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id
|
||||
return "Atomic(" + dump_impl(p.child, visited) + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_gbnf_parser>) {
|
||||
return "Gbnf(" + p.grammar + ", " + dump_impl(p.child, visited) + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_ac_parser>) {
|
||||
return "Ac(" + string_join(p.delimiters, " | ") + ", " + dump_impl(p.child, visited) + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_any_parser>) {
|
||||
return "Any";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_space_parser>) {
|
||||
@@ -1183,18 +995,7 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id
|
||||
} else if constexpr (std::is_same_v<T, common_peg_string_parser>) {
|
||||
return "String(" + std::string(1, p.delimiter) + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_until_parser>) {
|
||||
std::vector<std::string> branches;
|
||||
for (const auto & branch : p.branches) {
|
||||
auto text = dump_impl(branch.delimiter, visited);
|
||||
if (branch.rest != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
text += " " + dump_impl(branch.rest, visited);
|
||||
}
|
||||
branches.push_back(std::move(text));
|
||||
}
|
||||
if (p.include) {
|
||||
return "Until(" + dump_impl(p.content, visited) + ", " + string_join(branches, " | ") + (p.optional ? ", optional" : "") + ")";
|
||||
}
|
||||
return "Until(" + string_join(branches, " | ") + ")";
|
||||
return "Until(" + string_join(p.delimiters, " | ") + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_schema_parser>) {
|
||||
return "Schema(" + dump_impl(p.child, visited) + ", " + (p.node ? common_chat_schema::kind_name(p.node->kind()) : "null") + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_rule_parser>) {
|
||||
@@ -1202,9 +1003,9 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id
|
||||
} else if constexpr (std::is_same_v<T, common_peg_ref_parser>) {
|
||||
return "Ref(" + p.name + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_tag_parser>) {
|
||||
return "Tag(" + p.tag + ", " + dump_impl(p.child, visited) + ")";
|
||||
return "Tag(" + p.tag + ", " + dump(p.child) + ")";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_atomic_parser>) {
|
||||
return "Atomic(" + dump_impl(p.child, visited) + ")";
|
||||
return "Atomic(" + dump(p.child) + ")";
|
||||
} else {
|
||||
return "Unknown";
|
||||
}
|
||||
@@ -1288,67 +1089,6 @@ common_peg_parser operator|(const std::string & str, const common_peg_parser & p
|
||||
|
||||
common_peg_parser_builder::common_peg_parser_builder() {}
|
||||
|
||||
common_peg_parser_builder::common_peg_parser_builder(common_peg_tokens tokens) {
|
||||
arena_.tokens_ = std::move(tokens);
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::until_one_of(const std::vector<std::string> & delimiters) {
|
||||
common_peg_until_parser p;
|
||||
for (const auto & d : delimiters) {
|
||||
p.branches.push_back({ literal(d).id() });
|
||||
}
|
||||
p.matcher = build_until_matcher(arena_, p.branches, p.include);
|
||||
return add(std::move(p));
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::until(const common_peg_parser & delimiter) {
|
||||
common_peg_until_parser p;
|
||||
p.branches = { { delimiter.id() } };
|
||||
p.matcher = build_until_matcher(arena_, p.branches, p.include);
|
||||
return add(std::move(p));
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::through(const common_peg_parser & content, const std::vector<common_peg_until_branch> & branches, bool optional) {
|
||||
if (branches.empty()) {
|
||||
throw std::runtime_error("through requires at least one branch");
|
||||
}
|
||||
common_peg_until_parser p;
|
||||
p.branches = branches;
|
||||
p.include = true;
|
||||
p.optional = optional;
|
||||
p.content = content.id();
|
||||
p.matcher = build_until_matcher(arena_, p.branches, p.include);
|
||||
return add(std::move(p));
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::token(const std::string & piece) {
|
||||
auto token = arena_.tokens_.token_id(piece);
|
||||
if (token == LLAMA_TOKEN_NULL) {
|
||||
return literal(piece);
|
||||
}
|
||||
return add(common_peg_token_parser{token, piece});
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::token(const std::vector<std::string> & pieces, bool negate) {
|
||||
if (!negate) {
|
||||
std::vector<common_peg_parser> alts;
|
||||
for (const auto & piece : pieces) {
|
||||
alts.push_back(token(piece));
|
||||
}
|
||||
return choice(alts);
|
||||
}
|
||||
|
||||
common_peg_token_not_parser p;
|
||||
for (const auto & piece : pieces) {
|
||||
auto token = arena_.tokens_.token_id(piece);
|
||||
if (token == LLAMA_TOKEN_NULL) {
|
||||
throw std::invalid_argument("token is not registered with the builder: " + piece);
|
||||
}
|
||||
p.tokens.push_back(token);
|
||||
}
|
||||
return add(p);
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::sequence(const std::vector<common_peg_parser_id> & parsers) {
|
||||
// Flatten nested sequences
|
||||
std::vector<common_peg_parser_id> flattened;
|
||||
@@ -1455,17 +1195,6 @@ common_peg_parser common_peg_parser_builder::rule(const std::string & name, cons
|
||||
return ref(clean_name);
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::trigger_rule(const std::string & name, const common_peg_parser & start, const common_peg_parser & rest) {
|
||||
common_trie scratch;
|
||||
if (insert_delimiter(scratch, arena_, start.id()).count(0)) {
|
||||
throw std::invalid_argument("trigger start must not match the empty string");
|
||||
}
|
||||
auto clean_name = gbnf_format_rule_name(name);
|
||||
auto rule_id = arena_.add_parser(common_peg_rule_parser{clean_name, (start + rest).id(), true, start.id(), rest.id()});
|
||||
arena_.add_rule(clean_name, rule_id);
|
||||
return ref(clean_name);
|
||||
}
|
||||
|
||||
void common_peg_parser_builder::set_root(const common_peg_parser & p) {
|
||||
arena_.set_root(p.id());
|
||||
}
|
||||
@@ -1663,6 +1392,13 @@ common_peg_parser common_peg_parser_builder::json_member(const std::string & key
|
||||
});
|
||||
}
|
||||
|
||||
common_peg_parser common_peg_parser_builder::ac(const common_peg_parser & p, const std::vector<std::string> & delimiters) {
|
||||
if (delimiters.empty()) {
|
||||
throw std::runtime_error("ac parser requires at least one delimiter");
|
||||
}
|
||||
return add(common_peg_ac_parser{p, delimiters});
|
||||
}
|
||||
|
||||
static std::string gbnf_escape_char_class(uint32_t c) {
|
||||
if (c == '-' || c == ']' || c == '[' || c == '\\') {
|
||||
return "\\" + std::string(1, (char) c);
|
||||
@@ -1721,63 +1457,15 @@ static std::string gbnf_char_class(const std::vector<uint32_t> & chars, bool neg
|
||||
return s + "]";
|
||||
}
|
||||
|
||||
// Token set such as <[1,5-9]>, with consecutive ids collapsed into ranges
|
||||
static std::string gbnf_token_set(const std::vector<uint32_t> & tokens, bool negate) {
|
||||
std::string s = negate ? "!<[" : "<[";
|
||||
for (size_t i = 0; i < tokens.size();) {
|
||||
size_t j = i;
|
||||
while (j + 1 < tokens.size() && tokens[j + 1] == tokens[j] + 1) {
|
||||
j++;
|
||||
}
|
||||
s += (i == 0 ? "" : ",") + std::to_string(tokens[i]);
|
||||
if (j > i) {
|
||||
s += "-" + std::to_string(tokens[j]);
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
return s + "]>";
|
||||
}
|
||||
|
||||
// Symbols on the transitions out of an automaton state, codepoints and tokens kept apart
|
||||
struct gbnf_ac_symbols {
|
||||
std::vector<uint32_t> chars;
|
||||
std::vector<uint32_t> tokens;
|
||||
|
||||
void add(const common_trie::symbol & sym) {
|
||||
(sym.is_token() ? tokens : chars).push_back(sym.value);
|
||||
}
|
||||
|
||||
// One alternative for the codepoints and one for the tokens, each followed by next if given
|
||||
std::vector<std::string> alternatives(const std::string & next = "") const {
|
||||
std::vector<std::string> alts;
|
||||
const std::string tail = next.empty() ? "" : " " + next;
|
||||
if (!chars.empty()) {
|
||||
alts.push_back(gbnf_char_class(chars, false) + tail);
|
||||
}
|
||||
if (!tokens.empty()) {
|
||||
alts.push_back(gbnf_token_set(tokens, false) + tail);
|
||||
}
|
||||
return alts;
|
||||
}
|
||||
};
|
||||
|
||||
static std::string gbnf_ac_grammar(
|
||||
const common_grammar_builder & builder,
|
||||
const std::string & prefix,
|
||||
const common_trie & trie,
|
||||
const std::set<uint32_t> & opaque,
|
||||
const std::function<std::string(const gbnf_ac_symbols &,
|
||||
const std::map<size_t, gbnf_ac_symbols> &,
|
||||
const std::map<size_t, gbnf_ac_symbols> &,
|
||||
const std::string &,
|
||||
const common_grammar_builder & builder,
|
||||
const std::string & prefix,
|
||||
const std::vector<std::string> & strings,
|
||||
const std::function<std::string(const std::vector<uint32_t> &,
|
||||
const std::map<size_t, std::vector<uint32_t>> &,
|
||||
const std::vector<uint32_t> &,
|
||||
const std::function<std::string(size_t)> &)> & build_rule) {
|
||||
common_aho_corasick ac(trie);
|
||||
|
||||
// With only tokens in the alphabet, the grammar can step a whole token at a time
|
||||
bool token_only = true;
|
||||
for (const auto & sym : ac.alphabet) {
|
||||
token_only = token_only && sym.is_token();
|
||||
}
|
||||
common_aho_corasick ac(strings);
|
||||
|
||||
auto state_name = [&](size_t s) -> std::string {
|
||||
if (s == 0) {
|
||||
@@ -1793,43 +1481,27 @@ static std::string gbnf_ac_grammar(
|
||||
continue; // match states
|
||||
}
|
||||
|
||||
std::map<size_t, gbnf_ac_symbols> buckets;
|
||||
std::map<size_t, gbnf_ac_symbols> completing_to; // completing symbols by the match state they reach
|
||||
gbnf_ac_symbols completing; // symbols that complete a delimiter
|
||||
gbnf_ac_symbols specific; // symbols with an explicit transition
|
||||
for (const auto & sym : ac.alphabet) {
|
||||
size_t d = ac.next(q, sym);
|
||||
std::map<size_t, std::vector<uint32_t>> buckets;
|
||||
std::vector<uint32_t> completing; // chars that complete a delimiter
|
||||
std::vector<uint32_t> specific; // chars with an explicit transition
|
||||
for (uint32_t c : ac.alphabet) {
|
||||
size_t d = ac.next(q, c);
|
||||
if (ac.is_terminal(d)) {
|
||||
completing.add(sym);
|
||||
completing_to[d].add(sym);
|
||||
specific.add(sym);
|
||||
completing.push_back(c);
|
||||
specific.push_back(c);
|
||||
} else if (d != 0) {
|
||||
buckets[d].add(sym); // specific non-root destination
|
||||
specific.add(sym);
|
||||
buckets[d].push_back(c); // specific non-root destination
|
||||
specific.push_back(c);
|
||||
}
|
||||
}
|
||||
|
||||
// every other symbol goes back to the start
|
||||
std::string fallback;
|
||||
if (token_only) {
|
||||
fallback = gbnf_token_set(specific.tokens, true);
|
||||
} else {
|
||||
fallback = specific.chars.empty() ? "." : gbnf_char_class(specific.chars, true);
|
||||
builder.add_rule(state_name(q), build_rule(completing, buckets, specific, state_name));
|
||||
}
|
||||
|
||||
// Char rules never match a token named by a token rule, so allow the other named tokens by name
|
||||
std::vector<uint32_t> others;
|
||||
for (auto token : opaque) {
|
||||
if (std::find(specific.tokens.begin(), specific.tokens.end(), token) == specific.tokens.end()) {
|
||||
others.push_back(token);
|
||||
}
|
||||
}
|
||||
if (!others.empty()) {
|
||||
fallback = "(" + fallback + " | " + gbnf_token_set(others, false) + ")";
|
||||
}
|
||||
}
|
||||
fallback += " " + state_name(0);
|
||||
|
||||
builder.add_rule(state_name(q), build_rule(completing, completing_to, buckets, fallback, state_name));
|
||||
// An empty delimiter makes the start state terminal. Emit an entry rule
|
||||
// that matches the empty string so the returned reference stays valid.
|
||||
if (ac.is_terminal(0)) {
|
||||
builder.add_rule(prefix, "|");
|
||||
}
|
||||
|
||||
return state_name(0);
|
||||
@@ -1842,104 +1514,52 @@ static std::string gbnf_ac_grammar(
|
||||
// ref: https://github.com/ggml-org/llama.cpp/pull/24839
|
||||
static std::string gbnf_excluding_grammar(const common_grammar_builder & builder,
|
||||
const std::string & prefix,
|
||||
const common_trie & trie,
|
||||
const std::set<uint32_t> & opaque) {
|
||||
return gbnf_ac_grammar(builder, prefix, trie, opaque,
|
||||
[](const gbnf_ac_symbols & /*completing*/,
|
||||
const std::map<size_t, gbnf_ac_symbols> & /*completing_to*/,
|
||||
const std::map<size_t, gbnf_ac_symbols> & buckets,
|
||||
const std::string & fallback,
|
||||
const std::vector<std::string> & strings) {
|
||||
return gbnf_ac_grammar(builder, prefix, strings,
|
||||
[](const std::vector<uint32_t> & /*completing*/,
|
||||
const std::map<size_t, std::vector<uint32_t>> & buckets,
|
||||
const std::vector<uint32_t> & specific,
|
||||
const std::function<std::string(size_t)> & state_name) {
|
||||
// every state accepts and completing symbols get no alternative, so a forbidden string never matches
|
||||
// every state is accepting and completing chars get no
|
||||
// alternative, so a forbidden string can never be matched
|
||||
std::string rhs = "|";
|
||||
for (const auto & [d, symbols] : buckets) {
|
||||
for (const auto & alt : symbols.alternatives(state_name(d))) {
|
||||
rhs += " " + alt + " |";
|
||||
}
|
||||
for (const auto & [d, chars] : buckets) {
|
||||
rhs += " " + gbnf_char_class(chars, false) + " " + state_name(d) + " |";
|
||||
}
|
||||
rhs += " " + fallback;
|
||||
rhs += " " + gbnf_char_class(specific, true) + " " + state_name(0);
|
||||
return rhs;
|
||||
});
|
||||
}
|
||||
|
||||
// GBNF grammar matching up to the first pattern in the trie, then the rest rule of that pattern's value.
|
||||
// For the pattern "ab" with rest "x":
|
||||
//
|
||||
// prefix ::= [a] prefix-01 | [^a] prefix
|
||||
// prefix-01 ::= [b] rest | [a] prefix-01 | [^ab] prefix
|
||||
// rest ::= "x"
|
||||
static std::string gbnf_including_grammar(const common_grammar_builder & builder,
|
||||
const std::string & prefix,
|
||||
const common_trie & trie,
|
||||
const std::set<uint32_t> & opaque,
|
||||
const std::vector<std::string> & rests,
|
||||
bool optional) {
|
||||
common_aho_corasick ac(trie);
|
||||
|
||||
// every pattern ending at a match state, the longest and the ones reached by suffix links
|
||||
auto rests_at = [&](size_t s, bool & terminal) {
|
||||
std::vector<std::string> alts;
|
||||
terminal = false;
|
||||
for (; s != 0; s = ac.fail[s]) {
|
||||
auto pattern = ac.t.nodes[s].pattern;
|
||||
if (pattern < 0) {
|
||||
continue;
|
||||
}
|
||||
if (rests[pattern].empty()) {
|
||||
terminal = true;
|
||||
} else if (std::find(alts.begin(), alts.end(), rests[pattern]) == alts.end()) {
|
||||
alts.push_back(rests[pattern]);
|
||||
}
|
||||
}
|
||||
return alts;
|
||||
};
|
||||
|
||||
return gbnf_ac_grammar(builder, prefix, trie, opaque,
|
||||
[&](const gbnf_ac_symbols & /*completing*/,
|
||||
const std::map<size_t, gbnf_ac_symbols> & completing_to,
|
||||
const std::map<size_t, gbnf_ac_symbols> & buckets,
|
||||
const std::string & fallback,
|
||||
const std::function<std::string(size_t)> & state_name) {
|
||||
// GBNF grammar matching everything up to and including the first occurrence of
|
||||
// any string in `strings`. Emits the Aho-Corasick automaton DFA and returns
|
||||
// the start state rule name.
|
||||
static std::string gbnf_including_grammar(const common_grammar_builder & builder,
|
||||
const std::string & prefix,
|
||||
const std::vector<std::string> & strings) {
|
||||
return gbnf_ac_grammar(builder, prefix, strings,
|
||||
[](const std::vector<uint32_t> & completing,
|
||||
const std::map<size_t, std::vector<uint32_t>> & buckets,
|
||||
const std::vector<uint32_t> & specific,
|
||||
const std::function<std::string(size_t)> & state_name) {
|
||||
std::vector<std::string> alts;
|
||||
gbnf_ac_symbols terminating; // symbols that complete a pattern with no rest
|
||||
for (const auto & [d, symbols] : completing_to) {
|
||||
bool terminal = false;
|
||||
auto rest = rests_at(d, terminal);
|
||||
if (!rest.empty()) {
|
||||
for (auto & alt : symbols.alternatives(rest.size() == 1 ? rest[0] : "(" + string_join(rest, " | ") + ")")) {
|
||||
alts.push_back(std::move(alt));
|
||||
}
|
||||
}
|
||||
if (terminal) {
|
||||
terminating.chars.insert(terminating.chars.end(), symbols.chars.begin(), symbols.chars.end());
|
||||
terminating.tokens.insert(terminating.tokens.end(), symbols.tokens.begin(), symbols.tokens.end());
|
||||
}
|
||||
if (!completing.empty()) {
|
||||
alts.push_back(gbnf_char_class(completing, false)); // terminate on match
|
||||
}
|
||||
for (auto & alt : terminating.alternatives()) {
|
||||
alts.push_back(std::move(alt));
|
||||
for (const auto & [d, chars] : buckets) {
|
||||
alts.push_back(gbnf_char_class(chars, false) + " " + state_name(d));
|
||||
}
|
||||
for (const auto & [d, symbols] : buckets) {
|
||||
for (auto & alt : symbols.alternatives(state_name(d))) {
|
||||
alts.push_back(std::move(alt));
|
||||
}
|
||||
}
|
||||
// every other symbol keeps scanning from the start state
|
||||
alts.push_back(fallback);
|
||||
return (optional ? "| " : "") + string_join(alts, " | ");
|
||||
// every other character keeps scanning from the start state
|
||||
alts.push_back(gbnf_char_class(specific, true) + " " + state_name(0));
|
||||
return string_join(alts, " | ");
|
||||
});
|
||||
}
|
||||
|
||||
// The rules and the tokens named by token rules that the grammar of a parser reaches
|
||||
struct common_peg_reachable {
|
||||
std::set<std::string> rules;
|
||||
std::set<uint32_t> tokens;
|
||||
};
|
||||
|
||||
static void collect_reachable(
|
||||
static std::set<std::string> collect_reachable_rules(
|
||||
const common_peg_arena & arena,
|
||||
const common_peg_parser_id & root,
|
||||
common_peg_reachable & reachable
|
||||
const common_peg_parser_id & rule
|
||||
) {
|
||||
std::set<std::string> reachable;
|
||||
std::set<std::string> visited;
|
||||
|
||||
std::function<void(common_peg_parser_id)> visit = [&](common_peg_parser_id id) {
|
||||
@@ -1951,27 +1571,13 @@ static void collect_reachable(
|
||||
if constexpr (std::is_same_v<T, common_peg_epsilon_parser> ||
|
||||
std::is_same_v<T, common_peg_start_parser> ||
|
||||
std::is_same_v<T, common_peg_end_parser> ||
|
||||
std::is_same_v<T, common_peg_until_parser> ||
|
||||
std::is_same_v<T, common_peg_literal_parser> ||
|
||||
std::is_same_v<T, common_peg_chars_parser> ||
|
||||
std::is_same_v<T, common_peg_space_parser> ||
|
||||
std::is_same_v<T, common_peg_any_parser> ||
|
||||
std::is_same_v<T, common_peg_string_parser>) {
|
||||
// These parsers do not have any children
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_parser>) {
|
||||
reachable.tokens.insert(p.token);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_not_parser>) {
|
||||
reachable.tokens.insert(p.tokens.begin(), p.tokens.end());
|
||||
} else if constexpr (std::is_same_v<T, common_peg_until_parser>) {
|
||||
// The delimiters name their tokens in the grammar
|
||||
if (p.content != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
visit(p.content);
|
||||
}
|
||||
for (const auto & branch : p.branches) {
|
||||
visit(branch.delimiter);
|
||||
if (branch.rest != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
visit(branch.rest);
|
||||
}
|
||||
}
|
||||
} else if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
|
||||
for (auto child : p.children) {
|
||||
visit(child);
|
||||
@@ -1986,12 +1592,13 @@ static void collect_reachable(
|
||||
std::is_same_v<T, common_peg_tag_parser> ||
|
||||
std::is_same_v<T, common_peg_atomic_parser> ||
|
||||
std::is_same_v<T, common_peg_gbnf_parser> ||
|
||||
std::is_same_v<T, common_peg_ac_parser> ||
|
||||
std::is_same_v<T, common_peg_schema_parser>) {
|
||||
visit(p.child);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_rule_parser>) {
|
||||
if (visited.find(p.name) == visited.end()) {
|
||||
visited.insert(p.name);
|
||||
reachable.rules.insert(p.name);
|
||||
reachable.insert(p.name);
|
||||
visit(p.child);
|
||||
}
|
||||
} else if constexpr (std::is_same_v<T, common_peg_ref_parser>) {
|
||||
@@ -2004,13 +1611,12 @@ static void collect_reachable(
|
||||
}, parser);
|
||||
};
|
||||
|
||||
visit(root);
|
||||
visit(rule);
|
||||
return reachable;
|
||||
}
|
||||
|
||||
// GBNF generation implementation
|
||||
void common_peg_arena::build_grammar(const common_grammar_builder & builder, bool lazy) const {
|
||||
common_peg_reachable reachable;
|
||||
|
||||
// A raw string value is parsed by the child rather than constrained by the schema
|
||||
auto schema_delegates = [](const common_peg_schema_parser & s) -> bool {
|
||||
return !s.node || (s.raw && s.node->may_be_string());
|
||||
@@ -2049,10 +1655,6 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo
|
||||
return "";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_literal_parser>) {
|
||||
return gbnf_format_literal(p.literal);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_parser>) {
|
||||
return "<[" + std::to_string(p.token) + "]>";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_token_not_parser>) {
|
||||
return gbnf_token_set(std::vector<uint32_t>(p.tokens.begin(), p.tokens.end()), true);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_sequence_parser>) {
|
||||
std::string s;
|
||||
for (const auto & child : p.children) {
|
||||
@@ -2144,19 +1746,10 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo
|
||||
const std::string delim(1, p.delimiter);
|
||||
return R"(( [^)" + delim + R"(\\] | "\\" ( [)" + delim + R"(\\/ bfnrt] | "u" [0-9a-fA-F]{4} ) )*)";
|
||||
} else if constexpr (std::is_same_v<T, common_peg_until_parser>) {
|
||||
auto prefix = "until-" + std::to_string(id);
|
||||
if (!p.include) {
|
||||
if (p.branches.empty()) {
|
||||
return ".*";
|
||||
}
|
||||
return gbnf_excluding_grammar(builder, prefix, p.matcher, reachable.tokens);
|
||||
if (p.delimiters.empty()) {
|
||||
return ".*";
|
||||
}
|
||||
std::vector<std::string> branch_rests;
|
||||
for (size_t b = 0; b < p.branches.size(); b++) {
|
||||
auto rest = p.branches[b].rest;
|
||||
branch_rests.push_back(rest == COMMON_PEG_INVALID_PARSER_ID ? "" : builder.add_rule(prefix + "-rest-" + std::to_string(b), to_gbnf(rest)));
|
||||
}
|
||||
return gbnf_including_grammar(builder, prefix, p.matcher, reachable.tokens, branch_rests, p.optional);
|
||||
return gbnf_excluding_grammar(builder, "until-" + std::to_string(id), p.delimiters);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_schema_parser>) {
|
||||
if (schema_delegates(p)) {
|
||||
return to_gbnf(p.child);
|
||||
@@ -2173,52 +1766,38 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo
|
||||
return to_gbnf(p.child);
|
||||
} else if constexpr (std::is_same_v<T, common_peg_gbnf_parser>) {
|
||||
return p.grammar;
|
||||
} else if constexpr (std::is_same_v<T, common_peg_ac_parser>) {
|
||||
return gbnf_including_grammar(builder, "ac-" + std::to_string(id), p.delimiters);
|
||||
} else {
|
||||
static_assert(is_always_false_v<T>);
|
||||
}
|
||||
}, parser);
|
||||
};
|
||||
|
||||
// Trigger rules, sorted for a predictable order
|
||||
std::vector<const common_peg_rule_parser *> trigger_rules;
|
||||
for (const auto & [name, id] : rules_) {
|
||||
if (auto rule = std::get_if<common_peg_rule_parser>(&parsers_.at(id))) {
|
||||
if (rule->trigger) {
|
||||
trigger_rules.push_back(rule);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::sort(trigger_rules.begin(), trigger_rules.end(), [](const auto * a, const auto * b) { return a->name < b->name; });
|
||||
// Collect reachable rules
|
||||
std::set<std::string> reachable_rules;
|
||||
|
||||
// A lazy grammar scans for the starts when the trigger rules were built from a start and rest
|
||||
bool scans = false;
|
||||
for (const auto * rule : trigger_rules) {
|
||||
scans = scans || rule->start != COMMON_PEG_INVALID_PARSER_ID;
|
||||
}
|
||||
if (scans) {
|
||||
for (const auto * rule : trigger_rules) {
|
||||
if (rule->start == COMMON_PEG_INVALID_PARSER_ID) {
|
||||
throw std::runtime_error("trigger rule without a start in a scanning grammar: " + rule->name);
|
||||
if (lazy) {
|
||||
// Collect rules reachable from trigger rules
|
||||
for (const auto & [name, id] : rules_) {
|
||||
const auto & parser = parsers_.at(id);
|
||||
if (auto rule = std::get_if<common_peg_rule_parser>(&parser)) {
|
||||
if (rule->trigger) {
|
||||
// Mark trigger as reachable and visit it
|
||||
reachable_rules.insert(name);
|
||||
auto add_rules = collect_reachable_rules(*this, id);
|
||||
reachable_rules.insert(add_rules.begin(), add_rules.end());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (lazy && scans) {
|
||||
for (const auto * rule : trigger_rules) {
|
||||
collect_reachable(*this, rule->start, reachable);
|
||||
collect_reachable(*this, rule->rest, reachable);
|
||||
}
|
||||
} else if (lazy) {
|
||||
for (const auto * rule : trigger_rules) {
|
||||
collect_reachable(*this, rules_.at(rule->name), reachable);
|
||||
}
|
||||
} else {
|
||||
collect_reachable(*this, root_, reachable);
|
||||
// Collect rules reachable from root
|
||||
reachable_rules = collect_reachable_rules(*this, root_);
|
||||
}
|
||||
|
||||
// Create GBNF rules for all reachable rules
|
||||
for (const auto & [name, rule_id] : rules_) {
|
||||
if (reachable.rules.find(name) == reachable.rules.end()) {
|
||||
if (reachable_rules.find(name) == reachable_rules.end()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -2228,27 +1807,20 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo
|
||||
}
|
||||
}
|
||||
|
||||
if (lazy && scans) {
|
||||
// The root scans for a trigger start and then constrains its rest
|
||||
common_trie starts;
|
||||
std::vector<std::string> rests;
|
||||
for (const auto * rule : trigger_rules) {
|
||||
auto value = (int32_t) rests.size();
|
||||
rests.push_back(builder.add_rule(rule->name + "-rest", to_gbnf(rule->rest)));
|
||||
for (size_t end : insert_delimiter(starts, *this, rule->start)) {
|
||||
auto owner = starts.mark(end, value);
|
||||
if (owner != value) {
|
||||
throw std::runtime_error("trigger rules " + trigger_rules[owner]->name + " and " + rule->name + " must not share a start");
|
||||
if (lazy) {
|
||||
// Generate root rule from trigger rules only
|
||||
std::vector<std::string> trigger_names;
|
||||
for (const auto & [name, rule_id] : rules_) {
|
||||
const auto & parser = parsers_.at(rule_id);
|
||||
if (auto rule = std::get_if<common_peg_rule_parser>(&parser)) {
|
||||
if (rule->trigger) {
|
||||
trigger_names.push_back(rule->name);
|
||||
}
|
||||
}
|
||||
}
|
||||
builder.add_rule("root", gbnf_including_grammar(builder, "trigger", starts, reachable.tokens, rests, /* optional = */ true));
|
||||
} else if (lazy) {
|
||||
// Generate root rule from trigger rules only
|
||||
std::vector<std::string> trigger_names;
|
||||
for (const auto * rule : trigger_rules) {
|
||||
trigger_names.push_back(rule->name);
|
||||
}
|
||||
|
||||
// Sort for predictable order
|
||||
std::sort(trigger_names.begin(), trigger_names.end());
|
||||
builder.add_rule("root", string_join(trigger_names, " | "));
|
||||
} else if (root_ != COMMON_PEG_INVALID_PARSER_ID) {
|
||||
builder.add_rule("root", to_gbnf(root_));
|
||||
|
||||
+17
-77
@@ -3,7 +3,6 @@
|
||||
#include "json-schema.h"
|
||||
#include "json.h"
|
||||
#include "llama.h"
|
||||
#include "trie.h"
|
||||
|
||||
#include <memory>
|
||||
#include <set>
|
||||
@@ -189,22 +188,6 @@ struct common_peg_recursion_error : std::invalid_argument {
|
||||
using std::invalid_argument::invalid_argument;
|
||||
};
|
||||
|
||||
struct common_peg_token {
|
||||
std::string text;
|
||||
llama_token_attr attr;
|
||||
};
|
||||
|
||||
struct common_peg_tokens {
|
||||
std::unordered_map<llama_token, common_peg_token> tokens;
|
||||
std::unordered_map<std::string, llama_token> ids;
|
||||
|
||||
common_peg_tokens() = default;
|
||||
explicit common_peg_tokens(const llama_vocab * vocab);
|
||||
|
||||
// LLAMA_TOKEN_NULL if text is not a special token
|
||||
llama_token token_id(const std::string & text) const;
|
||||
};
|
||||
|
||||
struct common_peg_parse_context {
|
||||
std::string input; // [h, e, l, l, o, _, w, o, r, l, d]
|
||||
std::vector<llama_token> tokens; // [id, -1, -1, -1, -1, id, -1, -1, -1, -1, -1]
|
||||
@@ -243,16 +226,6 @@ struct common_peg_literal_parser {
|
||||
std::string literal;
|
||||
};
|
||||
|
||||
struct common_peg_token_parser {
|
||||
llama_token token;
|
||||
std::string piece;
|
||||
};
|
||||
|
||||
// Matches one token that is not one of the tokens
|
||||
struct common_peg_token_not_parser {
|
||||
std::vector<llama_token> tokens;
|
||||
};
|
||||
|
||||
struct common_peg_sequence_parser {
|
||||
std::vector<common_peg_parser_id> children;
|
||||
};
|
||||
@@ -297,18 +270,8 @@ struct common_peg_string_parser {
|
||||
char delimiter;
|
||||
};
|
||||
|
||||
// A delimiter an until parser stops at, and the parser that follows it when the delimiter is consumed
|
||||
struct common_peg_until_branch {
|
||||
common_peg_parser_id delimiter;
|
||||
common_peg_parser_id rest = COMMON_PEG_INVALID_PARSER_ID;
|
||||
};
|
||||
|
||||
struct common_peg_until_parser {
|
||||
std::vector<common_peg_until_branch> branches;
|
||||
bool include = false; // consume the first delimiter and parse the rest of its branch
|
||||
bool optional = false; // with include, the input may end before any delimiter
|
||||
common_peg_parser_id content = COMMON_PEG_INVALID_PARSER_ID; // with include, parsed up to the delimiter
|
||||
common_trie matcher; // each pattern valued by its branch
|
||||
std::vector<std::string> delimiters;
|
||||
};
|
||||
|
||||
struct common_peg_schema_parser {
|
||||
@@ -325,9 +288,6 @@ struct common_peg_rule_parser {
|
||||
std::string name;
|
||||
common_peg_parser_id child;
|
||||
bool trigger;
|
||||
// set when the rule has a start and rest, the lazy grammar scans for the start
|
||||
common_peg_parser_id start = COMMON_PEG_INVALID_PARSER_ID;
|
||||
common_peg_parser_id rest = COMMON_PEG_INVALID_PARSER_ID;
|
||||
};
|
||||
|
||||
struct common_peg_ref_parser {
|
||||
@@ -348,14 +308,17 @@ struct common_peg_gbnf_parser {
|
||||
std::string grammar;
|
||||
};
|
||||
|
||||
struct common_peg_ac_parser {
|
||||
common_peg_parser_id child;
|
||||
std::vector<std::string> delimiters;
|
||||
};
|
||||
|
||||
// Variant holding all parser types
|
||||
using common_peg_parser_variant = std::variant<
|
||||
common_peg_epsilon_parser,
|
||||
common_peg_start_parser,
|
||||
common_peg_end_parser,
|
||||
common_peg_literal_parser,
|
||||
common_peg_token_parser,
|
||||
common_peg_token_not_parser,
|
||||
common_peg_sequence_parser,
|
||||
common_peg_choice_parser,
|
||||
common_peg_repetition_parser,
|
||||
@@ -371,14 +334,14 @@ using common_peg_parser_variant = std::variant<
|
||||
common_peg_ref_parser,
|
||||
common_peg_atomic_parser,
|
||||
common_peg_tag_parser,
|
||||
common_peg_gbnf_parser
|
||||
common_peg_gbnf_parser,
|
||||
common_peg_ac_parser
|
||||
>;
|
||||
|
||||
class common_peg_arena {
|
||||
std::vector<common_peg_parser_variant> parsers_;
|
||||
std::unordered_map<std::string, common_peg_parser_id> rules_;
|
||||
common_peg_parser_id root_ = COMMON_PEG_INVALID_PARSER_ID;
|
||||
common_peg_tokens tokens_;
|
||||
|
||||
public:
|
||||
const common_peg_parser_variant & get(common_peg_parser_id id) const { return parsers_.at(id); }
|
||||
@@ -393,8 +356,6 @@ class common_peg_arena {
|
||||
common_peg_parser_id root() const { return root_; }
|
||||
void set_root(common_peg_parser_id id) { root_ = id; }
|
||||
|
||||
const common_peg_tokens & tokens() const { return tokens_; }
|
||||
|
||||
common_peg_parse_result parse(common_peg_parse_context & ctx, size_t start = 0) const;
|
||||
common_peg_parse_result parse(common_peg_parser_id id, common_peg_parse_context & ctx, size_t start) const;
|
||||
|
||||
@@ -423,7 +384,6 @@ class common_peg_parser_builder {
|
||||
|
||||
public:
|
||||
common_peg_parser_builder();
|
||||
explicit common_peg_parser_builder(common_peg_tokens tokens);
|
||||
|
||||
// Match nothing, always succeed.
|
||||
// S -> ε
|
||||
@@ -441,16 +401,6 @@ class common_peg_parser_builder {
|
||||
// S -> "hello"
|
||||
common_peg_parser literal(const std::string & literal) { return add(common_peg_literal_parser{literal}); }
|
||||
|
||||
// Matches a token. Falls back to a literal if the token is not registered with the builder.
|
||||
// S -> <[token-id]>
|
||||
common_peg_parser token(const std::string & piece);
|
||||
|
||||
// Matches one of the tokens. With negate, matches one token that is not in the set.
|
||||
// A negated set may only name tokens registered with the builder.
|
||||
// S -> <[id1]> | <[id2]> | ... or !<[id1,id2,...]>
|
||||
common_peg_parser token(const std::vector<std::string> & pieces, bool negate = false);
|
||||
common_peg_parser token(std::initializer_list<std::string> pieces, bool negate = false) { return token(std::vector<std::string>(pieces), negate); }
|
||||
|
||||
// Matches a sequence of parsers in order, all must succeed.
|
||||
// S -> A B C
|
||||
common_peg_parser sequence() { return add(common_peg_sequence_parser{}); }
|
||||
@@ -507,29 +457,16 @@ class common_peg_parser_builder {
|
||||
// Matches all characters until a delimiter is found (delimiter not consumed).
|
||||
// Invalid UTF-8 is consumed and recorded on the AST nodes.
|
||||
// S -> (!delim .)*
|
||||
common_peg_parser until(const std::string & delimiter) { return until_one_of({delimiter}); }
|
||||
common_peg_parser until(const std::string & delimiter) { return add(common_peg_until_parser{{delimiter}}); }
|
||||
|
||||
// Matches all characters until one of the delimiters in the list is found (delimiter not consumed).
|
||||
// S -> (!delim .)*
|
||||
common_peg_parser until_one_of(const std::vector<std::string> & delimiters);
|
||||
|
||||
// Matches all characters until the delimiter is found (delimiter not consumed).
|
||||
// The delimiter may only be a sequence of literals, tokens, and choices of them. Tags and atomics may wrap them.
|
||||
// S -> (!delim .)*
|
||||
common_peg_parser until(const common_peg_parser & delimiter);
|
||||
common_peg_parser until_one_of(const std::vector<std::string> & delimiters) { return add(common_peg_until_parser{delimiters}); }
|
||||
|
||||
// Matches everything
|
||||
// S -> .*
|
||||
common_peg_parser rest() { return until_one_of({}); }
|
||||
|
||||
// Matches content, then the first delimiter, then the rest of the branch of that delimiter.
|
||||
// Branches must not share a delimiter. With optional, the input may end before any delimiter.
|
||||
// S -> C (D1 R1 | D2 R2 | ...)
|
||||
common_peg_parser through(const common_peg_parser & content, const std::vector<common_peg_until_branch> & branches, bool optional = false);
|
||||
common_peg_parser through(const common_peg_parser & content, std::initializer_list<common_peg_until_branch> branches, bool optional = false) { return through(content, std::vector<common_peg_until_branch>(branches), optional); }
|
||||
common_peg_parser through(const common_peg_parser & content, const common_peg_parser & delimiter) { return through(content, { { delimiter } }); }
|
||||
common_peg_parser through(const common_peg_parser & content, const std::string & delimiter) { return through(content, literal(delimiter)); }
|
||||
|
||||
// Matches between min and max repetitions of a parser (inclusive).
|
||||
// S -> A{m,n}
|
||||
// Use -1 for max to represent unbounded repetition (equivalent to {m,})
|
||||
@@ -600,10 +537,6 @@ class common_peg_parser_builder {
|
||||
common_peg_parser trigger_rule(const std::string & name, const common_peg_parser & p) { return rule(name, p, true); }
|
||||
common_peg_parser trigger_rule(const std::string & name, const std::function<common_peg_parser()> & builder) { return rule(name, builder, true); }
|
||||
|
||||
// Creates a trigger rule that matches start followed by rest. A lazy grammar scans for the start of any such rule, then only allows its rest.
|
||||
// The start has the same limits as an until() delimiter.
|
||||
common_peg_parser trigger_rule(const std::string & name, const common_peg_parser & start, const common_peg_parser & rest);
|
||||
|
||||
// Creates an atomic parser. Atomic parsers do not create an AST node if
|
||||
// the child results in a partial parse, i.e. NEEDS_MORE_INPUT. This is
|
||||
// intended for situations where partial output is undesirable.
|
||||
@@ -617,6 +550,13 @@ class common_peg_parser_builder {
|
||||
// the child's grammar. Parsing delegates entirely to the child.
|
||||
common_peg_parser gbnf(const common_peg_parser & p, const std::string & grammar) { return add(common_peg_gbnf_parser{p, grammar}); }
|
||||
|
||||
// Wraps a child parser but emits a GBNF grammar built from the Aho-Corasick
|
||||
// automaton of `delimiters`, matching everything up to and including the
|
||||
// first delimiter. Parsing delegates entirely to the child, which is
|
||||
// responsible for consuming the delimiter (e.g. until(D) + literal(D)).
|
||||
common_peg_parser ac(const common_peg_parser & p, const std::vector<std::string> & delimiters);
|
||||
common_peg_parser ac(const common_peg_parser & p, const std::string & delimiter) { return ac(p, std::vector<std::string>{delimiter}); }
|
||||
|
||||
void set_root(const common_peg_parser & p);
|
||||
|
||||
common_peg_arena build();
|
||||
|
||||
@@ -31,18 +31,14 @@ struct token_matcher {
|
||||
static common_trie build_trie(const std::vector<llama_tokens> & seqs) {
|
||||
common_trie t;
|
||||
for (const auto & seq : seqs) {
|
||||
std::vector<common_trie::symbol> symbols;
|
||||
for (llama_token token : seq) {
|
||||
symbols.push_back(common_trie::symbol::token(token));
|
||||
}
|
||||
t.insert(symbols);
|
||||
t.insert(std::vector<uint32_t>(seq.begin(), seq.end()));
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
// returns the index into seqs of the longest sequence ending at this token, or -1
|
||||
int32_t advance(llama_token token) {
|
||||
state = ac.next(state, common_trie::symbol::token(token));
|
||||
state = ac.next(state, (uint32_t) token);
|
||||
const int32_t p = ac.match_pattern(state);
|
||||
if (p >= 0) {
|
||||
state = 0;
|
||||
|
||||
+1
-9
@@ -203,13 +203,6 @@ 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;
|
||||
@@ -262,8 +255,7 @@ struct common_sampler * common_sampler_init(
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw std::runtime_error(
|
||||
"unknown grammar trigger type: " + std::to_string(trigger.type));
|
||||
GGML_ASSERT(false && "unknown trigger type");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+253
-585
File diff suppressed because it is too large
Load Diff
@@ -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-dflash2 sample
|
||||
// candidate distribution per drafted token; set it to make draft-simple, draft-mtp and draft-dflash (DFlash2 only) sample
|
||||
std::vector<std::vector<llama_token_data>> * result_q = nullptr;
|
||||
|
||||
// the target's temp and seed, read only when the drafter samples probabilistically
|
||||
|
||||
+20
-54
@@ -4,46 +4,26 @@
|
||||
|
||||
#include <deque>
|
||||
|
||||
common_trie::step common_trie::next(std::string_view sv, const std::vector<int32_t> & token_map, size_t pos) const {
|
||||
if (!tokens.empty() && pos < token_map.size()) {
|
||||
const int32_t id = token_map[pos];
|
||||
if (id >= 0 && tokens.find(id) != tokens.end()) {
|
||||
size_t end = pos + 1;
|
||||
while (end < token_map.size() && token_map[end] < 0) {
|
||||
++end;
|
||||
}
|
||||
return { utf8_parse_result::SUCCESS, symbol::token(id), end - pos };
|
||||
}
|
||||
}
|
||||
|
||||
auto result = common_parse_utf8_codepoint(sv, pos);
|
||||
return { result.status, symbol::codepoint(result.codepoint), result.bytes_consumed };
|
||||
}
|
||||
|
||||
common_trie::match_result common_trie::check_at(std::string_view sv, size_t start_pos) const {
|
||||
return check_at(sv, {}, start_pos);
|
||||
}
|
||||
|
||||
common_trie::match_result common_trie::check_at(std::string_view sv, const std::vector<int32_t> & token_map, size_t start_pos) const {
|
||||
size_t current = 0; // Start at root
|
||||
size_t pos = start_pos;
|
||||
|
||||
// LOG_DBG("%s: checking at pos %zu, sv='%s'\n", __func__, start_pos, std::string(sv).c_str());
|
||||
|
||||
while (pos < sv.size()) {
|
||||
auto step = next(sv, token_map, pos);
|
||||
if (step.status != utf8_parse_result::SUCCESS) {
|
||||
auto result = common_parse_utf8_codepoint(sv, pos);
|
||||
if (result.status != utf8_parse_result::SUCCESS) {
|
||||
break;
|
||||
}
|
||||
|
||||
auto it = nodes[current].children.find(step.symbol);
|
||||
auto it = nodes[current].children.find(result.codepoint);
|
||||
if (it == nodes[current].children.end()) {
|
||||
// Can't continue matching
|
||||
return match_result{match_result::NO_MATCH};
|
||||
}
|
||||
|
||||
current = it->second;
|
||||
pos += step.bytes_consumed;
|
||||
pos += result.bytes_consumed;
|
||||
|
||||
// Check if we've matched a complete word
|
||||
if (nodes[current].pattern >= 0) {
|
||||
@@ -62,7 +42,7 @@ common_trie::match_result common_trie::check_at(std::string_view sv, const std::
|
||||
}
|
||||
|
||||
int32_t common_trie::insert(const std::string & word) {
|
||||
std::vector<symbol> symbols;
|
||||
std::vector<uint32_t> symbols;
|
||||
size_t pos = 0;
|
||||
while (pos < word.length()) {
|
||||
auto result = common_parse_utf8_codepoint(word, pos);
|
||||
@@ -70,42 +50,28 @@ int32_t common_trie::insert(const std::string & word) {
|
||||
break;
|
||||
}
|
||||
|
||||
symbols.push_back(symbol::codepoint(result.codepoint));
|
||||
symbols.push_back(result.codepoint);
|
||||
pos += result.bytes_consumed;
|
||||
}
|
||||
return insert(symbols);
|
||||
}
|
||||
|
||||
int32_t common_trie::insert(const std::vector<symbol> & symbols) {
|
||||
int32_t common_trie::insert(const std::vector<uint32_t> & symbols) {
|
||||
size_t current = 0;
|
||||
for (symbol ch : symbols) {
|
||||
current = extend(current, ch);
|
||||
for (uint32_t ch : symbols) {
|
||||
auto it = nodes[current].children.find(ch);
|
||||
if (it == nodes[current].children.end()) {
|
||||
size_t child = create_node();
|
||||
nodes[current].children[ch] = child;
|
||||
current = child;
|
||||
} else {
|
||||
current = it->second;
|
||||
}
|
||||
}
|
||||
int32_t pattern = mark(current, n_patterns);
|
||||
if (pattern == n_patterns) {
|
||||
n_patterns++;
|
||||
if (nodes[current].pattern < 0) {
|
||||
nodes[current].pattern = n_patterns++;
|
||||
}
|
||||
return pattern;
|
||||
}
|
||||
|
||||
size_t common_trie::extend(size_t node, symbol ch) {
|
||||
if (ch.is_token()) {
|
||||
tokens.insert((int32_t) ch.value);
|
||||
}
|
||||
auto it = nodes[node].children.find(ch);
|
||||
if (it != nodes[node].children.end()) {
|
||||
return it->second;
|
||||
}
|
||||
size_t child = create_node();
|
||||
nodes[node].children[ch] = child;
|
||||
return child;
|
||||
}
|
||||
|
||||
int32_t common_trie::mark(size_t node, int32_t value) {
|
||||
if (nodes[node].pattern < 0) {
|
||||
nodes[node].pattern = value;
|
||||
}
|
||||
return nodes[node].pattern;
|
||||
return nodes[current].pattern;
|
||||
}
|
||||
|
||||
common_aho_corasick::common_aho_corasick(common_trie trie) : t(std::move(trie)) {
|
||||
@@ -147,7 +113,7 @@ common_aho_corasick::common_aho_corasick(common_trie trie) : t(std::move(trie))
|
||||
}
|
||||
}
|
||||
|
||||
size_t common_aho_corasick::next(size_t state, common_trie::symbol ch) const {
|
||||
size_t common_aho_corasick::next(size_t state, uint32_t ch) const {
|
||||
const auto & nodes = t.nodes;
|
||||
while (state && nodes[state].children.find(ch) == nodes[state].children.end()) {
|
||||
state = fail[state];
|
||||
|
||||
+10
-51
@@ -1,7 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include "unicode.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <set>
|
||||
@@ -12,42 +10,13 @@
|
||||
// Trie for matching multiple literals.
|
||||
// This is used in common_peg_until_parser and to build a GBNF exclusion grammar
|
||||
struct common_trie {
|
||||
// A symbol is either a UTF-8 codepoint or a token
|
||||
struct symbol {
|
||||
enum kind_type : uint8_t { CODEPOINT, TOKEN };
|
||||
|
||||
kind_type kind = CODEPOINT;
|
||||
uint32_t value = 0;
|
||||
|
||||
static symbol codepoint(uint32_t cpt) { return { CODEPOINT, cpt }; }
|
||||
static symbol token(int32_t id) { return { TOKEN, (uint32_t) id }; }
|
||||
|
||||
bool is_token() const { return kind == TOKEN; }
|
||||
|
||||
bool operator<(const symbol & other) const {
|
||||
return kind != other.kind ? kind < other.kind : value < other.value;
|
||||
}
|
||||
bool operator==(const symbol & other) const {
|
||||
return kind == other.kind && value == other.value;
|
||||
}
|
||||
};
|
||||
|
||||
struct step {
|
||||
enum utf8_parse_result::status status;
|
||||
common_trie::symbol symbol;
|
||||
size_t bytes_consumed;
|
||||
};
|
||||
|
||||
struct node {
|
||||
std::map<symbol, size_t> children;
|
||||
std::map<uint32_t, size_t> children; // Use uint32_t to store Unicode codepoints
|
||||
int32_t pattern = -1; // index of the pattern ending at this node, -1 if none
|
||||
};
|
||||
|
||||
std::vector<node> nodes;
|
||||
|
||||
// every token id used by a pattern, the input is split so these match as single symbols
|
||||
std::set<int32_t> tokens;
|
||||
|
||||
common_trie() {
|
||||
create_node(); // root node
|
||||
}
|
||||
@@ -60,25 +29,15 @@ struct common_trie {
|
||||
|
||||
enum match_result { NO_MATCH, PARTIAL_MATCH, COMPLETE_MATCH };
|
||||
|
||||
// Read the symbol at pos. It is a token if a pattern uses the token at pos, else a UTF-8 codepoint.
|
||||
step next(std::string_view sv, const std::vector<int32_t> & token_map, size_t pos) const;
|
||||
|
||||
// Check if a delimiter starts at the given position
|
||||
match_result check_at(std::string_view sv, size_t start_pos) const;
|
||||
match_result check_at(std::string_view sv, const std::vector<int32_t> & token_map, size_t start_pos) const;
|
||||
|
||||
// Insert a word as a sequence of Unicode codepoints, returns its pattern index
|
||||
int32_t insert(const std::string & word);
|
||||
|
||||
// Insert a symbol sequence, returns its pattern index (insertion order, duplicates keep the first index)
|
||||
int32_t insert(const std::vector<symbol> & symbols);
|
||||
|
||||
// Child of node on a symbol, created if missing
|
||||
size_t extend(size_t node, symbol ch);
|
||||
|
||||
// Mark node as the end of a pattern with a value from the caller. Returns the value already there, or value if the node had none.
|
||||
// A trie must take its values from mark or from insert, not both.
|
||||
int32_t mark(size_t node, int32_t value);
|
||||
// Insert a raw symbol sequence, returns its pattern index (insertion order,
|
||||
// duplicates keep the first index)
|
||||
int32_t insert(const std::vector<uint32_t> & symbols);
|
||||
|
||||
private:
|
||||
int32_t n_patterns = 0;
|
||||
@@ -92,11 +51,11 @@ struct common_trie {
|
||||
|
||||
// Aho-Corasick automaton
|
||||
struct common_aho_corasick {
|
||||
common_trie t;
|
||||
std::vector<size_t> fail; // failure links
|
||||
std::vector<size_t> order; // states in BFS order
|
||||
std::vector<int32_t> match; // longest pattern ending at each state (directly or via a suffix link), -1 if none
|
||||
std::set<common_trie::symbol> alphabet; // every symbol with a transition
|
||||
common_trie t;
|
||||
std::vector<size_t> fail; // failure links
|
||||
std::vector<size_t> order; // states in BFS order
|
||||
std::vector<int32_t> match; // longest pattern ending at each state (directly or via a suffix link), -1 if none
|
||||
std::set<uint32_t> alphabet; // every character with a transition
|
||||
|
||||
common_aho_corasick(common_trie trie);
|
||||
|
||||
@@ -110,5 +69,5 @@ struct common_aho_corasick {
|
||||
int32_t match_pattern(size_t s) const { return match[s]; }
|
||||
|
||||
// follow failure links until a transition on `ch` exists.
|
||||
size_t next(size_t state, common_trie::symbol ch) const;
|
||||
size_t next(size_t state, uint32_t ch) const;
|
||||
};
|
||||
|
||||
@@ -78,7 +78,6 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"DistilBertForMaskedLM": "bert",
|
||||
"DistilBertForSequenceClassification": "bert",
|
||||
"DistilBertModel": "bert",
|
||||
"DomynEdgeForCausalLM": "domynedge",
|
||||
"Dots1ForCausalLM": "dots1",
|
||||
"Dots3NoteForCausalLM": "dots3",
|
||||
"Dots3NoteForConditionalGeneration": "dots3",
|
||||
@@ -127,7 +126,6 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"GlmOcrForConditionalGeneration": "glm",
|
||||
"GptOssForCausalLM": "gpt_oss",
|
||||
"GraniteForCausalLM": "granite",
|
||||
"Granite4VisionForConditionalGeneration": "granite",
|
||||
"GraniteMoeForCausalLM": "granite",
|
||||
"GraniteMoeHybridForCausalLM": "granite",
|
||||
"GraniteMoeSharedForCausalLM": "granite",
|
||||
@@ -139,7 +137,6 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"Grok1ForCausalLM": "grok",
|
||||
"GrokForCausalLM": "grok",
|
||||
"GroveMoeForCausalLM": "grovemoe",
|
||||
"HiggsAudio3Model": "higgs_audio",
|
||||
"HunYuanDenseV1ForCausalLM": "hunyuan",
|
||||
"HunYuanMoEV1ForCausalLM": "hunyuan",
|
||||
"HunYuanVLForConditionalGeneration": "hunyuan",
|
||||
@@ -147,10 +144,6 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"HYV3ForCausalLM": "hunyuan",
|
||||
"HYV4ForCausalLM": "hy_v4",
|
||||
"IQuestCoderForCausalLM": "llama",
|
||||
"Inkling2ForCausalLM": "inkling2",
|
||||
"Inkling2LoopForCausalLM": "inkling2",
|
||||
"Inkling2ForConditionalGeneration": "inkling2",
|
||||
"Inkling2LoopForConditionalGeneration": "inkling2",
|
||||
"InternLM2ForCausalLM": "internlm",
|
||||
"InternLM3ForCausalLM": "internlm",
|
||||
"JAISLMHeadModel": "jais",
|
||||
@@ -224,7 +217,6 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"MiniMaxM2ForCausalLM": "minimax",
|
||||
"MiniMaxM3SparseForCausalLM": "minimax",
|
||||
"MiniMaxM3SparseForConditionalGeneration": "minimax",
|
||||
"DSparkMiniMaxDraftModel": "minimax",
|
||||
"Ministral3ForCausalLM": "mistral3",
|
||||
"Ministral3Model": "mistral3",
|
||||
"Mistral3ForConditionalGeneration": "mistral3",
|
||||
@@ -286,13 +278,6 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"Qwen3NextForCausalLM": "qwen",
|
||||
"Qwen3OmniMoeForConditionalGeneration": "qwen3vl",
|
||||
"PocketTTSModel": "pockettts",
|
||||
"MoshiModel": "moshi",
|
||||
"KokoroModel": "kokoro",
|
||||
"TinyVocaModel": "tiny_voca",
|
||||
"Zonos3Model": "zonos3",
|
||||
"YuE2ForCausalLM": "yue2",
|
||||
"VoxCPM2Model": "voxcpm",
|
||||
"MiniMaxMusic3ForConditionalGeneration": "minimax_music3",
|
||||
"Qwen3TTSForConditionalGeneration": "qwen3tts",
|
||||
"Qwen3VLForConditionalGeneration": "qwen3vl",
|
||||
"Qwen3VLMoeForConditionalGeneration": "qwen3vl",
|
||||
@@ -335,7 +320,6 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"UMT5Model": "t5",
|
||||
"UltravoxModel": "ultravox",
|
||||
"UnlimitedOCRForCausalLM": "deepseek",
|
||||
"VibeVoiceAsrForConditionalGeneration": "vibevoice_asr",
|
||||
"VLlama3ForCausalLM": "llama",
|
||||
"VllmDecision2Model": "vllm_decision2",
|
||||
"VoxtralForConditionalGeneration": "llama",
|
||||
@@ -345,8 +329,6 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"XverseForCausalLM": "xverse",
|
||||
"YoutuForCausalLM": "deepseek",
|
||||
"YoutuVLForConditionalGeneration": "deepseek",
|
||||
"ZayaForCausalLM": "zaya1",
|
||||
"fish_qwen3_omni": "fish_s2",
|
||||
"modeling_grove_moe.GroveMoeForCausalLM": "grovemoe",
|
||||
"modeling_sarvam_moe.SarvamMoEForCausalLM": "bailingmoe",
|
||||
}
|
||||
@@ -370,10 +352,6 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
|
||||
"EmbeddingGemma2Model": "gemma",
|
||||
"Exaone4_5_ForConditionalGeneration": "exaone",
|
||||
"FishOmniModel": "drama3",
|
||||
"Zonos3Model": "zonos3",
|
||||
"YuE2ForCausalLM": "yue2",
|
||||
"VoxCPM2Model": "voxcpm",
|
||||
"MiniMaxMusic3ForConditionalGeneration": "minimax_music3",
|
||||
"Gemma3ForConditionalGeneration": "gemma",
|
||||
"Gemma3nForConditionalGeneration": "gemma",
|
||||
"Gemma4ForConditionalGeneration": "gemma",
|
||||
@@ -388,11 +366,8 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
|
||||
"Granite4VisionForConditionalGeneration": "granite",
|
||||
"GraniteSpeechForConditionalGeneration": "granite",
|
||||
"GraniteSpeechPlusForConditionalGeneration": "granite",
|
||||
"HiggsAudio3Model": "higgs_audio",
|
||||
"HunYuanVLForConditionalGeneration": "hunyuan",
|
||||
"Idefics3ForConditionalGeneration": "smolvlm",
|
||||
"Inkling2ForConditionalGeneration": "inkling2",
|
||||
"Inkling2LoopForConditionalGeneration": "inkling2",
|
||||
"InternVisionModel": "internvl",
|
||||
"JanusForConditionalGeneration": "januspro",
|
||||
"KimiK25ForConditionalGeneration": "kimivl",
|
||||
@@ -433,9 +408,6 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
|
||||
"Qwen3ASRForConditionalGeneration": "qwen3vl",
|
||||
"Qwen3OmniMoeForConditionalGeneration": "qwen3vl",
|
||||
"PocketTTSModel": "pockettts",
|
||||
"MoshiModel": "moshi",
|
||||
"KokoroModel": "kokoro",
|
||||
"TinyVocaModel": "tiny_voca",
|
||||
"SopranoModel": "soprano",
|
||||
"Qwen3TTSForConditionalGeneration": "qwen3tts",
|
||||
"Qwen3VLForConditionalGeneration": "qwen3vl",
|
||||
@@ -452,11 +424,9 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
|
||||
"Step3p7ForConditionalGeneration": "step3",
|
||||
"UltravoxModel": "ultravox",
|
||||
"UnlimitedOCRForCausalLM": "deepseek",
|
||||
"VibeVoiceAsrForConditionalGeneration": "vibevoice_asr",
|
||||
"VoxtralForConditionalGeneration": "ultravox",
|
||||
"VoxtralRealtimeForConditionalGeneration": "ultravox",
|
||||
"YoutuVLForConditionalGeneration": "youtuvl",
|
||||
"fish_qwen3_omni": "fish_s2",
|
||||
}
|
||||
|
||||
|
||||
|
||||
+4
-48
@@ -398,9 +398,6 @@ class ModelBase:
|
||||
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]
|
||||
@@ -541,7 +538,7 @@ class ModelBase:
|
||||
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", "mxfp8"): # bsgemm-moe: drama-3, same block layout
|
||||
elif quant_method in ("fp8", "bsgemm-moe"): # 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"):
|
||||
@@ -653,28 +650,6 @@ class ModelBase:
|
||||
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}")
|
||||
|
||||
@@ -1382,10 +1357,10 @@ class ModelBase:
|
||||
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|w1|w2|w3)\.weight$', name)
|
||||
m = re.search(r'\.experts\.(\d+)\.(gate_proj|up_proj|down_proj)\.weight$', name)
|
||||
if m:
|
||||
expert_id = int(m.group(1))
|
||||
proj_type = {"w1": "gate_proj", "w2": "down_proj", "w3": "up_proj"}.get(m.group(2), m.group(2))
|
||||
proj_type = 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)
|
||||
@@ -1476,8 +1451,6 @@ class ModelBase:
|
||||
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
|
||||
|
||||
@@ -2006,14 +1979,6 @@ class TextModel(ModelBase):
|
||||
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}")
|
||||
@@ -2467,12 +2432,6 @@ class TextModel(ModelBase):
|
||||
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 chkhsh == "32d85c31273f8019248f2559fed492d929ea28b17e51d81d3bb36fff23ca72b3":
|
||||
# ref: https://huggingface.co/domyn/Domyn-Edge-Teacher-IF
|
||||
res = "domyn-edge"
|
||||
|
||||
if res is None:
|
||||
logger.warning("\n")
|
||||
@@ -3502,7 +3461,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", "HiggsAudio3Model"):
|
||||
if model_type == ModelType.TEXT and arch in ("NEOChatModel", "StepVLForConditionalGeneration", "Sarashina2VisionForCausalLM", "Exaone4_5_ForConditionalGeneration", "Step3p7ForConditionalGeneration", "KimiK3ForConditionalGeneration", "KimiK31ForConditionalGeneration", "Nemotron3_5TranscribeForConditionalGeneration"):
|
||||
return arch
|
||||
|
||||
# if "architectures" is found in the sub-config, use that instead
|
||||
@@ -3513,9 +3472,6 @@ 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
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
from .base import TextModel, ModelBase
|
||||
import gguf
|
||||
|
||||
|
||||
@ModelBase.register("DomynEdgeForCausalLM")
|
||||
@ModelBase.example("domyn/Domyn-Edge-Teacher-IF")
|
||||
class DomynEdgeModel(TextModel):
|
||||
model_arch = gguf.MODEL_ARCH.DOMYN_EDGE
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
super().set_gguf_parameters()
|
||||
hparams = self.hparams
|
||||
self.gguf_writer.add_vocab_size(hparams["vocab_size"])
|
||||
|
||||
position_layers = hparams["position_layers"] # list of "rope"/"nope" strings per layer
|
||||
head_sizes = hparams["head_sizes"] # list of int head dims per layer
|
||||
|
||||
# Per-layer rope/SWA pattern: True="rope", False="nope"
|
||||
rope_pattern = [v == "rope" for v in position_layers]
|
||||
self.gguf_writer.add_rope_pattern(rope_pattern)
|
||||
self.gguf_writer.add_sliding_window_pattern(rope_pattern) # SWA <-> RoPE in domyn-edge
|
||||
|
||||
# window_sizes entries are flash-attn style [left, right] (current token excluded; -1 = full attention),
|
||||
# while llama.cpp's n_swa counts the current token, hence the +1 (matches HF's sliding_window=1025)
|
||||
swa_window = hparams.get("sliding_window")
|
||||
if swa_window is None:
|
||||
window_sizes = hparams.get("window_sizes") # list of [size, offset] pairs per layer
|
||||
if window_sizes is None:
|
||||
raise KeyError("Neither `sliding_window` nor `window_sizes` found among domyn edge hyperparameters")
|
||||
left = next((ws[0] for v, ws in zip(position_layers, window_sizes) if v == "rope"), None)
|
||||
swa_window = left + 1 if left is not None and left > 0 else None
|
||||
if swa_window is None:
|
||||
raise ValueError("No sliding window size found among domyn edge hyperparameters")
|
||||
self.gguf_writer.add_sliding_window(swa_window)
|
||||
|
||||
# Head dims differ between full-attention ("nope") and SWA ("rope") layers
|
||||
full_head_dims = {h for v, h in zip(position_layers, head_sizes) if v == "nope"}
|
||||
swa_head_dims = {h for v, h in zip(position_layers, head_sizes) if v == "rope"}
|
||||
|
||||
if len(full_head_dims) != 1:
|
||||
raise ValueError(f"Expected one head dimension for full attention layers, found {len(full_head_dims)}")
|
||||
full_head_dim = full_head_dims.pop()
|
||||
|
||||
self.gguf_writer.add_key_length(full_head_dim)
|
||||
self.gguf_writer.add_value_length(full_head_dim)
|
||||
|
||||
if len(swa_head_dims) != 1:
|
||||
raise ValueError(f"Expected one head dimension for SWA attention layers, found {len(swa_head_dims)}")
|
||||
swa_head_dim = swa_head_dims.pop()
|
||||
|
||||
self.gguf_writer.add_key_length_swa(swa_head_dim)
|
||||
self.gguf_writer.add_value_length_swa(swa_head_dim)
|
||||
self.gguf_writer.add_rope_dimension_count_swa(swa_head_dim)
|
||||
+22
-162
@@ -18,139 +18,6 @@ _TOWER_SHARED = "audio_decoder_mtp_shared.layers."
|
||||
_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)
|
||||
|
||||
|
||||
# codec encoder strides (encoder_rates of the codec config), the quantizer then downsamples 2x2
|
||||
_CODEC_ENC_STRIDES = (2, 4, 8, 8)
|
||||
|
||||
# codec encoder transformers, both 1024 wide with 16 heads of 64
|
||||
# generic audio layers a.blk.0..3: last encoder block, a.blk.4..11: quantizer pre_module
|
||||
_N_ENC_TFM_LAYERS = 4
|
||||
_N_PRE_TFM_LAYERS = 8
|
||||
_CODEC_HEAD_DIM = 64
|
||||
|
||||
|
||||
def _neox_rows(w: Tensor, head_dim: int) -> Tensor:
|
||||
# checkpoint uses interleaved RoPE, reorder the rows of each head so NEOX RoPE gives the same result
|
||||
order = torch.cat([torch.arange(0, head_dim, 2), torch.arange(1, head_dim, 2)])
|
||||
return w.reshape(-1, head_dim, *w.shape[1:])[:, order].reshape(w.shape)
|
||||
|
||||
|
||||
def codec_encoder_tensors(sd: dict[str, Tensor], num_codebooks: int) -> Iterable[tuple[str, Tensor]]:
|
||||
T = gguf.MODEL_TENSOR
|
||||
|
||||
def get(name: str) -> Tensor:
|
||||
return sd[name].float()
|
||||
|
||||
def tn(tensor: gguf.MODEL_TENSOR, bid: int | None = None, xid: int | None = None) -> str:
|
||||
return gguf.TENSOR_NAMES[tensor].format(bid=bid, xid=xid)
|
||||
|
||||
def fmt(tensor: gguf.MODEL_TENSOR, bid: int | None = None, suffix: str = ".weight") -> str:
|
||||
return tn(tensor, bid) + suffix
|
||||
|
||||
def conv_wb(tensor: gguf.MODEL_TENSOR, prefix: str, bid: int | None = None, xid: int | None = None, stride: int = 1):
|
||||
# taps-major [K / stride, OC, stride * IC], see conv() in tools/mtmd/models/fish-s2-spkenc.cpp
|
||||
w = fold_conv(sd, prefix)
|
||||
n_out, n_in, k = w.shape
|
||||
w = w.reshape(n_out, n_in, k // stride, stride).permute(2, 0, 3, 1).reshape(k // stride, n_out, stride * n_in)
|
||||
yield (tn(tensor, bid, xid) + ".weight", w)
|
||||
yield (tn(tensor, bid, xid) + ".bias", get(prefix + ".conv.bias"))
|
||||
|
||||
def snake_ab(tensor: gguf.MODEL_TENSOR, name: str, bid: int | None = None, xid: int | None = None):
|
||||
a, b = fold_snake(get(name))
|
||||
yield (tn(tensor, bid, xid) + ".alpha", a)
|
||||
yield (tn(tensor, bid, xid) + ".beta", b)
|
||||
|
||||
def tfm_layers(prefix: str, n_layer: int, offset: int):
|
||||
for il in range(n_layer):
|
||||
p = f"{prefix}layers.{il}."
|
||||
bid = offset + il
|
||||
wq, wk, wv = get(p + "attention.wqkv.weight").chunk(3, dim=0)
|
||||
yield (fmt(T.A_ENC_ATTN_Q, bid), _neox_rows(wq, _CODEC_HEAD_DIM))
|
||||
yield (fmt(T.A_ENC_ATTN_K, bid), _neox_rows(wk, _CODEC_HEAD_DIM))
|
||||
yield (fmt(T.A_ENC_ATTN_V, bid), wv)
|
||||
yield (fmt(T.A_ENC_OUTPUT, bid), get(p + "attention.wo.weight"))
|
||||
yield (fmt(T.A_ENC_INPUT_NORM, bid), get(p + "attention_norm.weight"))
|
||||
yield (fmt(T.A_ENC_ATTN_SCALE, bid), get(p + "attention_layer_scale.gamma"))
|
||||
yield (fmt(T.A_ENC_OUTPUT_NORM, bid), get(p + "ffn_norm.weight"))
|
||||
yield (fmt(T.A_ENC_FFN_GATE, bid), get(p + "feed_forward.w1.weight"))
|
||||
yield (fmt(T.A_ENC_FFN_UP, bid), get(p + "feed_forward.w3.weight"))
|
||||
yield (fmt(T.A_ENC_FFN_DOWN, bid), get(p + "feed_forward.w2.weight"))
|
||||
yield (fmt(T.A_ENC_FFN_SCALE_LS, bid), get(p + "ffn_layer_scale.gamma"))
|
||||
|
||||
# encoder: entry conv, 4x (3 residual units, Snake, strided conv), Snake, post conv
|
||||
e = "encoder.block."
|
||||
yield from conv_wb(T.A_CODEC_ENC_ENTRY, e + "0")
|
||||
for bid, stride in enumerate(_CODEC_ENC_STRIDES):
|
||||
p = f"{e}{bid + 1}.block."
|
||||
for xid in range(3):
|
||||
r = f"{p}{xid}.block."
|
||||
yield from snake_ab(T.A_CODEC_ENC_RES_ACT1, r + "0.alpha", bid, xid)
|
||||
yield from conv_wb(T.A_CODEC_ENC_RES_CONV1, r + "1", bid, xid)
|
||||
yield from snake_ab(T.A_CODEC_ENC_RES_ACT2, r + "2.alpha", bid, xid)
|
||||
yield from conv_wb(T.A_CODEC_ENC_RES_CONV2, r + "3", bid, xid)
|
||||
yield from snake_ab(T.A_CODEC_ENC_SNAKE, p + "3.alpha", bid)
|
||||
yield from conv_wb(T.A_CODEC_ENC_CONV, p + "4", bid, stride=stride)
|
||||
# the last block ends with a windowed transformer
|
||||
yield from tfm_layers(f"{e}4.block.5.", _N_ENC_TFM_LAYERS, 0)
|
||||
yield (fmt(T.A_POST_NORM), get(f"{e}4.block.5.norm.weight"))
|
||||
yield from snake_ab(T.A_CODEC_ENC_POST_SNAKE, e + "5.alpha")
|
||||
yield from conv_wb(T.A_CODEC_ENC_POST_CONV, e + "6")
|
||||
|
||||
# quantizer: 2x (strided conv + ConvNeXt), windowed transformer, then semantic + residual VQ
|
||||
q = "quantizer."
|
||||
for bid in range(2):
|
||||
p = f"{q}downsample.{bid}."
|
||||
yield from conv_wb(T.A_CODEC_DOWN_CONV, p + "0", bid, stride=2)
|
||||
# depthwise: one [C] row per tap
|
||||
yield (tn(T.A_CODEC_DOWN_DWCONV, bid) + ".weight", fold_conv(sd, p + "1.dwconv").squeeze(1).T.contiguous())
|
||||
yield (tn(T.A_CODEC_DOWN_DWCONV, bid) + ".bias", get(p + "1.dwconv.conv.bias"))
|
||||
for key, tensor in (("norm", T.A_CODEC_DOWN_NORM), ("pwconv1", T.A_CODEC_DOWN_PW1), ("pwconv2", T.A_CODEC_DOWN_PW2)):
|
||||
yield (tn(tensor, bid) + ".weight", get(f"{p}1.{key}.weight"))
|
||||
yield (tn(tensor, bid) + ".bias", get(f"{p}1.{key}.bias"))
|
||||
yield (tn(T.A_CODEC_DOWN_GAMMA, bid), get(p + "1.gamma"))
|
||||
yield from tfm_layers(q + "pre_module.", _N_PRE_TFM_LAYERS, _N_ENC_TFM_LAYERS)
|
||||
yield (fmt(T.A_CODEC_PRE_NORM), get(q + "pre_module.norm.weight"))
|
||||
|
||||
# nearest codebook entry by cosine similarity, see VectorQuantize.decode_latents()
|
||||
def vq(prefix: str) -> tuple[Tensor, Tensor, Tensor]:
|
||||
w = fold_wn(sd[prefix + ".in_proj.weight_g"], sd[prefix + ".in_proj.weight_v"])
|
||||
cb = torch.nn.functional.normalize(get(prefix + ".codebook.weight"), dim=-1)
|
||||
return w, get(prefix + ".in_proj.bias"), cb
|
||||
|
||||
w, b, cb = vq(q + "semantic_quantizer.quantizers.0")
|
||||
yield (fmt(T.A_CODEC_VQ_FIRST_IN, suffix=".weight"), w)
|
||||
yield (fmt(T.A_CODEC_VQ_FIRST_IN, suffix=".bias"), b)
|
||||
yield (fmt(T.A_CODEC_VQ_FIRST_CB), cb)
|
||||
n_rest = num_codebooks - 1
|
||||
rest = [vq(f"{q}quantizer.quantizers.{i}") for i in range(n_rest)]
|
||||
yield (fmt(T.A_CODEC_VQ_REST_IN, suffix=".weight"), torch.stack([r[0] for r in rest]))
|
||||
yield (fmt(T.A_CODEC_VQ_REST_IN, suffix=".bias"), torch.stack([r[1] for r in rest]))
|
||||
yield (fmt(T.A_CODEC_VQ_REST_CB), torch.stack([r[2] for r in rest]))
|
||||
|
||||
|
||||
@ModelBase.register("FishOmniModel")
|
||||
@ModelBase.example("fishaudio/drama-3")
|
||||
class Drama3TextModel(Qwen3_5MoeTextModel):
|
||||
@@ -168,8 +35,7 @@ class Drama3TextModel(Qwen3_5MoeTextModel):
|
||||
@ModelBase.example("fishaudio/drama-3")
|
||||
class Drama3MmprojModel(MmprojModel):
|
||||
has_vision_encoder = False
|
||||
has_audio_encoder = True # codec encoder, for voice cloning
|
||||
gen_projector_type = gguf.VisionProjectorType.DRAMA3_GEN
|
||||
has_audio_encoder = False
|
||||
|
||||
_LAYER_MAP = {
|
||||
"enorm.weight": (gguf.MODEL_TENSOR.A_GEN_CODE_ENORM, True),
|
||||
@@ -203,7 +69,7 @@ class Drama3MmprojModel(MmprojModel):
|
||||
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(self.gen_projector_type)
|
||||
self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.DRAMA3_GEN)
|
||||
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"])
|
||||
@@ -212,16 +78,6 @@ class Drama3MmprojModel(MmprojModel):
|
||||
self.gguf_writer.add_gen_audio_head_count_kv(cfg["n_local_heads"])
|
||||
self.gguf_writer.add_gen_audio_attention_layernorm_eps(cfg["norm_eps"])
|
||||
# other tower and codec hparams are hardcoded in tools/mtmd
|
||||
# codec encoder: raw 44.1 kHz waveform -> backbone input rows, other hparams are hardcoded in tools/mtmd
|
||||
self.gguf_writer.add_clip_has_audio_encoder(True)
|
||||
self.gguf_writer.add_clip_audio_projector_type(gguf.VisionProjectorType.FISH_S2_SPKENC)
|
||||
self.gguf_writer.add_audio_projection_dim(self.n_embd_text)
|
||||
self.gguf_writer.add_audio_num_mel_bins(1)
|
||||
self.gguf_writer.add_audio_block_count(_N_ENC_TFM_LAYERS + _N_PRE_TFM_LAYERS)
|
||||
self.gguf_writer.add_audio_embedding_length(1024)
|
||||
self.gguf_writer.add_audio_feed_forward_length(3072)
|
||||
self.gguf_writer.add_audio_head_count(1024 // _CODEC_HEAD_DIM)
|
||||
self.gguf_writer.add_audio_attention_layernorm_eps(1e-5)
|
||||
|
||||
@classmethod
|
||||
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
|
||||
@@ -231,12 +87,6 @@ class Drama3MmprojModel(MmprojModel):
|
||||
return None
|
||||
|
||||
def tensor_force_quant(self, name, new_name, bid, n_dims):
|
||||
# the VQ picks the nearest codebook entry, small errors in the encoder change the codes
|
||||
if new_name.startswith("a.codec."):
|
||||
return gguf.GGMLQuantizationType.F32
|
||||
# codec transformers: F16 gives codes closer to the reference than BF16
|
||||
if new_name.startswith("a.blk.") and n_dims == 2:
|
||||
return gguf.GGMLQuantizationType.F16
|
||||
# conv1d/conv1d_dw kernels must be F16, ggml_conv_1d(_dw) has no BF16 path
|
||||
if new_name.endswith(".weight") and (
|
||||
new_name in ("a.gen.wav.dac.entry.weight", "a.gen.wav.dac.post_conv.weight")
|
||||
@@ -255,7 +105,7 @@ class Drama3MmprojModel(MmprojModel):
|
||||
T = gguf.MODEL_TENSOR
|
||||
cfg = self.hparams
|
||||
|
||||
if name.startswith("a."):
|
||||
if name.startswith("a.gen.wav."):
|
||||
yield (name, data_torch)
|
||||
return
|
||||
|
||||
@@ -302,21 +152,33 @@ class Drama3MmprojModel(MmprojModel):
|
||||
raise ValueError(f"unexpected tensor {name}")
|
||||
|
||||
def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
|
||||
# Fish DAC decoder, then the shared codec encoder for voice cloning
|
||||
sd = load_codec(self.dir_model)
|
||||
# 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)
|
||||
T = gguf.MODEL_TENSOR
|
||||
|
||||
def get(name: str) -> Tensor:
|
||||
return sd[name].float()
|
||||
|
||||
def conv(prefix: str) -> Tensor:
|
||||
return fold_conv(sd, prefix)
|
||||
# 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)
|
||||
|
||||
def quant_table(prefix: str) -> Tensor:
|
||||
# fold out_proj into the codebook, so decoding is a row lookup
|
||||
w = fold_wn(sd[prefix + ".out_proj.weight_g"], sd[prefix + ".out_proj.weight_v"])
|
||||
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)
|
||||
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"))
|
||||
@@ -366,7 +228,7 @@ class Drama3MmprojModel(MmprojModel):
|
||||
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 = fold_snake(get(p + "0.alpha"))
|
||||
a, b = 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"))
|
||||
@@ -374,7 +236,7 @@ class Drama3MmprojModel(MmprojModel):
|
||||
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 = fold_snake(get(r + act + ".alpha"))
|
||||
a, b = snake(get(r + act + ".alpha"))
|
||||
name = gguf.TENSOR_NAMES[tensor].format(bid=bid, xid=xid)
|
||||
yield (name + ".alpha", a)
|
||||
yield (name + ".beta", b)
|
||||
@@ -382,10 +244,8 @@ class Drama3MmprojModel(MmprojModel):
|
||||
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 = fold_snake(get(d + "5.alpha"))
|
||||
a, b = 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"))
|
||||
yield (self.format_tensor_name(T.A_GEN_WAV_DAC_POST_CONV, suffix=".bias"), get(d + "6.conv.bias"))
|
||||
|
||||
yield from codec_encoder_tensors(sd, self.hparams["num_codebooks"])
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Iterable, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from torch import Tensor
|
||||
|
||||
from .base import ModelBase, gguf
|
||||
from .drama3 import Drama3MmprojModel, _neox_rows
|
||||
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
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
@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):
|
||||
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
|
||||
|
||||
@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)
|
||||
+10
-4
@@ -14,7 +14,7 @@ from .llama import LlamaModel
|
||||
from .mamba import Mamba2Model
|
||||
|
||||
|
||||
@ModelBase.register("GraniteForCausalLM", "Granite4VisionForConditionalGeneration")
|
||||
@ModelBase.register("GraniteForCausalLM")
|
||||
@ModelBase.example("ibm-granite/granite-3.3-2b-instruct")
|
||||
class GraniteModel(LlamaModel):
|
||||
"""Conversion for IBM's GraniteForCausalLM"""
|
||||
@@ -112,6 +112,14 @@ class GraniteSWAModel(GraniteModel):
|
||||
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):
|
||||
@@ -552,9 +560,7 @@ class GraniteHybridModel(Mamba2Model, GraniteMoeModel):
|
||||
or not self._ssm_layers
|
||||
)
|
||||
self.gguf_writer.add_rope_scaling_finetuned(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:
|
||||
if not use_rope:
|
||||
self.gguf_writer.add_context_length(2**20)
|
||||
|
||||
## Validation ##
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
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 -%}"
|
||||
"{{- '<think>\\n\\n</think>\\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)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user