diff --git a/.buildkite/hardware_tests/intel_xpu_ci/test-intel.yaml b/.buildkite/hardware_tests/intel_xpu_ci/test-intel.yaml new file mode 100644 index 000000000000..11c88a6043a9 --- /dev/null +++ b/.buildkite/hardware_tests/intel_xpu_ci/test-intel.yaml @@ -0,0 +1,68 @@ +group: Intel +steps: + - label: ":docker: Build XPU image" + soft_fail: true + optional: true + depends_on: [] + key: image-build-xpu + commands: + - bash -lc '.buildkite/image_build/image_build_xpu.sh "public.ecr.aws/q9t5s3a7" "vllm-ci-test-repo" "$BUILDKITE_COMMIT"' + env: + DOCKER_BUILDKIT: "1" + retry: + automatic: + - exit_status: -1 # Agent was lost + limit: 2 + - exit_status: -10 # Agent was lost + limit: 2 + - label: "XPU example Test" + depends_on: + - image-build-xpu + timeout_in_minutes: 30 + optional: true + device: intel_gpu + no_plugin: true + env: + REGISTRY: "public.ecr.aws/q9t5s3a7" + REPO: "vllm-ci-test-repo" + source_file_dependencies: + - .buildkite/hardware_tests/intel_xpu_ci/test-intel.yaml + - .buildkite/scripts/hardware_ci/run-intel-ci-test.sh + commands: + - >- + bash .buildkite/scripts/hardware_ci/run-intel-test.sh + 'bash .buildkite/scripts/hardware_ci/run-intel-ci-test.sh example' + - label: "XPU V1 test" + depends_on: + - image-build-xpu + timeout_in_minutes: 30 + optional: true + device: intel_gpu + no_plugin: true + env: + REGISTRY: "public.ecr.aws/q9t5s3a7" + REPO: "vllm-ci-test-repo" + source_file_dependencies: + - .buildkite/hardware_tests/intel_xpu_ci/test-intel.yaml + - .buildkite/scripts/hardware_ci/run-intel-ci-test.sh + commands: + - >- + bash .buildkite/scripts/hardware_ci/run-intel-test.sh + 'bash .buildkite/scripts/hardware_ci/run-intel-ci-test.sh v1' + - label: "XPU server test" + depends_on: + - image-build-xpu + timeout_in_minutes: 30 + optional: true + device: intel_gpu + no_plugin: true + env: + REGISTRY: "public.ecr.aws/q9t5s3a7" + REPO: "vllm-ci-test-repo" + source_file_dependencies: + - .buildkite/hardware_tests/intel_xpu_ci/test-intel.yaml + - .buildkite/scripts/hardware_ci/run-intel-ci-test.sh + commands: + - >- + bash .buildkite/scripts/hardware_ci/run-intel-test.sh + 'bash .buildkite/scripts/hardware_ci/run-intel-ci-test.sh server' diff --git a/.buildkite/intel_jobs/misc_intel.yaml b/.buildkite/intel_jobs/misc_intel.yaml index 20a9f5bd1734..d74494ed8b3e 100644 --- a/.buildkite/intel_jobs/misc_intel.yaml +++ b/.buildkite/intel_jobs/misc_intel.yaml @@ -57,13 +57,16 @@ steps: commands: - >- bash .buildkite/scripts/hardware_ci/run-intel-test.sh - 'export VLLM_WORKER_MULTIPROC_METHOD=spawn && + 'pip install lm_eval[api]>=0.4.12 && + export VLLM_WORKER_MULTIPROC_METHOD=spawn && cd tests && pytest -v -s v1/logits_processors --ignore=v1/logits_processors/test_custom_online.py --ignore=v1/logits_processors/test_custom_offline.py && pytest -v -s v1/test_oracle.py && pytest -v -s v1/test_request.py && pytest -v -s v1/test_outputs.py && - pytest -v -s v1/sample/test_topk_topp_sampler.py' + pytest -v -s v1/sample/test_topk_topp_sampler.py && + pytest -v -s v1/sample/test_logprobs.py && + pytest -v -s v1/sample/test_logprobs_e2e.py' - label: XPU CPU Offload timeout_in_minutes: 60 diff --git a/.buildkite/intel_jobs/model_runner_v2_intel.yaml b/.buildkite/intel_jobs/model_runner_v2_intel.yaml new file mode 100644 index 000000000000..67ce57ebd756 --- /dev/null +++ b/.buildkite/intel_jobs/model_runner_v2_intel.yaml @@ -0,0 +1,54 @@ +group: Model Runner V2 Intel +depends_on: + - image-build-xpu +steps: +- label: Model Runner V2 Core Tests (Intel) + timeout_in_minutes: 45 + device: intel_gpu + no_plugin: true + working_dir: "." + env: + REGISTRY: "public.ecr.aws/q9t5s3a7" + REPO: "vllm-ci-test-repo" + VLLM_TEST_DEVICE: "xpu" + source_file_dependencies: + - vllm/v1/worker/gpu/ + - vllm/v1/worker/gpu_worker.py + - vllm/v1/core/sched/ + - vllm/v1/attention/ + - tests/v1/engine/test_llm_engine.py + - tests/v1/e2e/ + commands: + - >- + bash .buildkite/scripts/hardware_ci/run-intel-test.sh + 'export VLLM_USE_V2_MODEL_RUNNER=1 && + cd tests && + pytest -v -s v1/engine/test_llm_engine.py -k "not test_engine_metrics" && + ENFORCE_EAGER=1 pytest -v -s v1/e2e/general/test_async_scheduling.py -k "not ngram" && + pytest -v -s v1/e2e/general/test_min_tokens.py' + +- label: Model Runner V2 Examples (Intel) + timeout_in_minutes: 45 + device: intel_gpu + no_plugin: true + working_dir: "." + env: + REGISTRY: "public.ecr.aws/q9t5s3a7" + REPO: "vllm-ci-test-repo" + VLLM_TEST_DEVICE: "xpu" + source_file_dependencies: + - vllm/v1/worker/gpu/ + - vllm/v1/core/sched/ + - vllm/v1/worker/gpu_worker.py + - examples/basic/offline_inference/ + - examples/generate/multimodal/ + - examples/features/ + commands: + - >- + bash .buildkite/scripts/hardware_ci/run-intel-test.sh + 'export VLLM_USE_V2_MODEL_RUNNER=1 && + cd examples && + python3 basic/offline_inference/chat.py && + python3 basic/offline_inference/generate.py --model facebook/opt-125m && + python3 generate/multimodal/vision_language_offline.py --seed 0 && + python3 features/automatic_prefix_caching/prefix_caching_offline.py' diff --git a/.buildkite/intel_jobs/test-intel.yaml b/.buildkite/intel_jobs/test-intel.yaml index 4bf14f7064be..afeb11e06d59 100644 --- a/.buildkite/intel_jobs/test-intel.yaml +++ b/.buildkite/intel_jobs/test-intel.yaml @@ -87,3 +87,20 @@ steps: cd tests && pytest -v -s entrypoints/multimodal/openai/chat_completion/test_audio_in_video.py && pytest -v -s benchmarks/test_serve_cli.py' + - label: "XPU quantization test" + depends_on: + - image-build-xpu + timeout_in_minutes: 30 + device: intel_gpu + no_plugin: true + env: + REGISTRY: "public.ecr.aws/q9t5s3a7" + REPO: "vllm-ci-test-repo" + source_file_dependencies: + - vllm/ + - .buildkite/intel_jobs/test-intel.yaml + commands: + - >- + bash .buildkite/scripts/hardware_ci/run-intel-test.sh + 'cd tests && + pytest -v -s quantization/test_auto_round.py' \ No newline at end of file diff --git a/.buildkite/release-pipeline.yaml b/.buildkite/release-pipeline.yaml index b31404bca154..897c98145341 100644 --- a/.buildkite/release-pipeline.yaml +++ b/.buildkite/release-pipeline.yaml @@ -1,12 +1,25 @@ # CUDA architecture lists — following PyTorch RELEASE.md # (https://github.com/pytorch/pytorch/blob/main/RELEASE.md) # SM86 included for broader Ampere coverage; SM89 for marlin fp8 support +# These requested arches are filtered by CMake's CUDA_SUPPORTED_ARCHS before +# per-kernel arch selection. Do not add +PTX here: top-level +PTX is stripped +# during that filtering, so kernels that need PTX must request it locally. env: - CUDA_ARCH_X86: "7.5 8.0 8.6 8.9 9.0 10.0 12.0+PTX" - # aarch64 only architectures: 8.7 for Orin, 11.0 for Thor (since CUDA 13) - CUDA_ARCH_AARCH64: "8.0 8.7 8.9 9.0 10.0 11.0 12.0+PTX" + # for CUDA >=13, sm_100+ targets have family specifiers (see CMakeLists.txt) + # so targets like 10.3 and 12.1 are automatically supported with this list + CUDA_ARCH_X86: "7.5 8.0 8.6 8.9 9.0 10.0 12.0" + # aarch64-only targets: Orin (8.7), Thor (11.0, CUDA 13+) + CUDA_ARCH_AARCH64: "8.0 8.7 8.9 9.0 10.0 11.0 12.0" + + # for CUDA <13, we need to specify all needed targets + # some targets (10.3, 12.1) are skipped to limit the wheel size (< 500MB) + # please use CUDA 13 wheels or compile yourself on these new devices CUDA_ARCH_X86_CU129: "7.5 8.0 8.6 8.9 9.0 10.0 12.0" CUDA_ARCH_AARCH64_CU129: "8.0 8.7 8.9 9.0 10.0 12.0" + + # pre-built mooncake wheels + # the manylinux_2_35 wheel has compatibility issue on Ubuntu 24.04 + # so we use different wheels for the time being MOONCAKE_WHEEL_AARCH64_2_35: "https://vllm-wheels.s3.amazonaws.com/mooncake/mooncake_transfer_engine-0.3.10.post2-0da9dfea3-cp312-cp312-manylinux_2_35_aarch64.whl" MOONCAKE_WHEEL_AARCH64_2_39: "https://vllm-wheels.s3.amazonaws.com/mooncake/mooncake_transfer_engine-0.3.10.post2-0da9dfea3-cp312-cp312-manylinux_2_39_aarch64.whl" MOONCAKE_WHEEL_X86_64: "https://vllm-wheels.s3.amazonaws.com/mooncake/mooncake_transfer_engine-0.3.10.post2-0da9dfea3-cp312-cp312-manylinux_2_35_x86_64.whl" diff --git a/.buildkite/scripts/ci-clean-log.sh b/.buildkite/scripts/ci-clean-log.sh index 69d8a3a28831..e2e21483d546 100644 --- a/.buildkite/scripts/ci-clean-log.sh +++ b/.buildkite/scripts/ci-clean-log.sh @@ -13,5 +13,8 @@ INPUT_FILE="$1" # Strip timestamps sed -i 's/^\[[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}T[0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\}Z\] //' "$INPUT_FILE" +# Strip Buildkite inline timestamp markers (ESC _bk;t= BEL) +sed -i 's/\x1B_bk;t=[0-9]*\x07//g' "$INPUT_FILE" + # Strip colorization sed -i -r 's/\x1B\[[0-9;]*[mK]//g' "$INPUT_FILE" diff --git a/.buildkite/scripts/ci-fetch-log.sh b/.buildkite/scripts/ci-fetch-log.sh index 3f99bc50a57d..4830135a1120 100755 --- a/.buildkite/scripts/ci-fetch-log.sh +++ b/.buildkite/scripts/ci-fetch-log.sh @@ -1,74 +1,178 @@ #!/bin/bash -# Usage: ./ci-fetch-log.sh [output_file] -# ./ci-fetch-log.sh [output_file] +# Fetch vLLM Buildkite CI logs (public; no login required). # -# Downloads the raw log for a Buildkite job from the public, unauthenticated -# /organizations//pipelines//builds//jobs//download -# endpoint, then strips ANSI/timestamps via ci-clean-log.sh. +# Usage: +# ci-fetch-log.sh [--soft|--all] --pr [] failed jobs in the PR's latest +# build (current branch if omitted) +# ci-fetch-log.sh [--soft|--all] failed jobs in that build +# ci-fetch-log.sh [output] one job; both # and +# ?sid= URL forms work +# ci-fetch-log.sh [output] # -# Find and via: -# gh pr checks --repo vllm-project/vllm -# Each failing row's URL is .../builds/#. -# -# Default output path: ci--.log (e.g. -# ci-68478-019e6b07-daae.log). Jobs in the same build share the UUID's -# first 8 chars, so the second segment is needed for uniqueness when -# fetching multiple jobs in parallel. The script refuses to overwrite an -# existing output file; pass an explicit path or set CI_FETCH_LOG_FORCE=1 -# to override. +# --soft also fetches soft-failed jobs; --all fetches every finished job. +# Saves each log as ci--.log (ANSI/timestamps stripped) and +# prints "\t" per job. [output] is single-job only; "-" +# streams to stdout. Existing files are kept; CI_FETCH_LOG_FORCE=1 refetches. set -euo pipefail ORG="vllm" PIPELINE="ci" +UA="vllm-ci-fetch-log" +UUID_RE='[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' usage() { - echo "Usage: $0 [output_file]" - echo " $0 [output_file]" + sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//' + exit 1 +} + +die() { + echo "$1" >&2 exit 1 } -if [ $# -lt 1 ]; then usage; fi +BUILD="" JOB="" SID="" OUT="" +SCOPE="failed" + +while :; do + case "${1:-}" in + --soft) SCOPE="soft" ;; + --all) SCOPE="all" ;; + *) break ;; + esac + shift +done -if [[ "$1" == https://* ]]; then +case "${1:-}" in +--pr) + PR="${2:-}" + # gh pr checks exits non-zero when checks are failing; that is the + # expected case here. + URL=$(gh pr checks ${PR:+"$PR"} --repo vllm-project/vllm 2>/dev/null | + grep -oE "https://buildkite.com/${ORG}/${PIPELINE}/builds/[0-9]+" | + sort -t/ -k7 -n | tail -1 || true) + [ -n "$URL" ] || die "No Buildkite build found via: gh pr checks ${PR:-}" + BUILD="${URL##*/}" + ;; +https://*) BUILD=$(echo "$1" | sed -nE 's#.*/builds/([0-9]+).*#\1#p') - JOB=$(echo "$1" | grep -oE '[0-9a-f]{8}-[0-9a-f-]+' | head -n 1) + JOB=$(echo "$1" | grep -oE "#${UUID_RE}" | head -n 1 | cut -c2- || true) + SID=$(echo "$1" | grep -oE "[?&]sid=${UUID_RE}" | head -n 1 | sed 's/.*sid=//' || true) OUT="${2:-}" -else - if [ $# -lt 2 ]; then usage; fi + [ -n "$BUILD" ] || die "Could not parse build number from: $1" + ;; +[0-9]*) + [ $# -ge 2 ] || usage BUILD="$1" JOB="$2" OUT="${3:-}" -fi - -if [ -z "$BUILD" ] || [ -z "$JOB" ]; then - echo "Could not parse build number or job UUID from: $1" >&2 + ;; +*) usage -fi + ;; +esac -# Jobs in the same build share the UUID's first segment, so include the -# second segment (chars 9-13, e.g. "019e6b07-daae") to keep default filenames -# unique when fetching multiple jobs from one build in parallel. -if [ -z "$OUT" ]; then - OUT="ci-${BUILD}-${JOB:0:13}.log" +COOKIES=$(mktemp) +JOBS_TSV=$(mktemp) +trap 'rm -f "$COOKIES" "$JOBS_TSV"' EXIT + +# Buildkite issues a session cookie on first hit; later requests need it. +curl -fsSL -c "$COOKIES" -A "$UA" \ + "https://buildkite.com/${ORG}/${PIPELINE}/builds/${BUILD}" -o /dev/null + +# The build's job list (id, step uuid, state, name) is served as JSON from +# the user-facing /data/jobs endpoint. Flatten it to TSV for easy filtering: +# job_id step_uuid failed soft_failed finished slug name +curl -fsSL -b "$COOKIES" -A "$UA" \ + "https://buildkite.com/${ORG}/${PIPELINE}/builds/${BUILD}/data/jobs" | + python3 -c ' +import json, re, sys + +data = json.load(sys.stdin) +if data.get("has_next_page"): + print("warning: job list is paginated; some jobs not shown", file=sys.stderr) +for r in data["records"]: + if r.get("type") != "script": + continue + name = (r.get("name") or "").replace("\t", " ").replace("\n", " ") + slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:60] + print("\t".join([ + r["id"], + r.get("step_uuid") or "", + str(r.get("passed") is False), + str(bool(r.get("soft_failed"))), + str(bool(r.get("finished_at"))), + slug, + name, + ])) +' >"$JOBS_TSV" || die "Could not list jobs for build ${BUILD}" + +if [ -n "$SID" ] && [ -z "$JOB" ]; then + # The ?sid= in builds//list URLs is the *step* uuid, not the job uuid. + JOB=$(awk -F'\t' -v s="$SID" '$1 == s || $2 == s {print $1; exit}' "$JOBS_TSV") + [ -n "$JOB" ] || die "No job matching sid=${SID} in build ${BUILD}" fi -if [ -e "$OUT" ] && [ -z "${CI_FETCH_LOG_FORCE:-}" ]; then - echo "Refusing to overwrite existing $OUT (set CI_FETCH_LOG_FORCE=1 or pass an explicit output path)." >&2 - exit 1 +fetch_job() { # + curl -fsSL -b "$COOKIES" -A "$UA" \ + "https://buildkite.com/organizations/${ORG}/pipelines/${PIPELINE}/builds/${BUILD}/jobs/$1/download" \ + -o "$2" + bash "$(dirname "$0")/ci-clean-log.sh" "$2" +} + +if [ -n "$JOB" ]; then + # Single-job mode. + NAME=$(awk -F'\t' -v j="$JOB" '$1 == j {print $7; exit}' "$JOBS_TSV") + SLUG=$(awk -F'\t' -v j="$JOB" '$1 == j {print $6; exit}' "$JOBS_TSV") + [ -n "$OUT" ] || OUT="ci-${BUILD}-${SLUG:-${JOB:0:13}}.log" + if [ "$OUT" = "-" ]; then + TMP=$(mktemp) + fetch_job "$JOB" "$TMP" + cat "$TMP" + rm -f "$TMP" + exit 0 + fi + if [ -e "$OUT" ] && [ -z "${CI_FETCH_LOG_FORCE:-}" ]; then + die "Refusing to overwrite existing ${OUT} (set CI_FETCH_LOG_FORCE=1 or pass an output path)." + fi + fetch_job "$JOB" "$OUT" + printf '%s\t%s\n' "$OUT" "${NAME:-$JOB}" + exit 0 fi -COOKIES=$(mktemp) -trap 'rm -f "$COOKIES"' EXIT +# Build-wide mode: fetch finished jobs matching $SCOPE. +[ -z "$OUT" ] || die "[output_file] is only valid when fetching a single job." -# Buildkite issues a session cookie on first hit; subsequent /download needs it. -curl -fsSL -c "$COOKIES" -A "vllm-ci-fetch-log" \ - "https://buildkite.com/${ORG}/${PIPELINE}/builds/${BUILD}" -o /dev/null +case "$SCOPE" in +failed) FILTER='$3 == "True" && $4 == "False" && $5 == "True"' ;; +soft) FILTER='$3 == "True" && $5 == "True"' ;; +all) FILTER='$5 == "True"' ;; +esac -curl -fsSL -b "$COOKIES" -A "vllm-ci-fetch-log" \ - "https://buildkite.com/organizations/${ORG}/pipelines/${PIPELINE}/builds/${BUILD}/jobs/${JOB}/download" \ - -o "$OUT" +if [ "$SCOPE" = "failed" ]; then + SOFT=$(awk -F'\t' '$3 == "True" && $4 == "True"' "$JOBS_TSV" | wc -l) + [ "$SOFT" -eq 0 ] || echo "Skipping ${SOFT} soft-failed job(s); use --soft to include them." >&2 +fi -bash "$(dirname "$0")/ci-clean-log.sh" "$OUT" +FOUND=0 +EMITTED=" " +while IFS=$'\t' read -r job_id _ _ _ _ slug name; do + FOUND=$((FOUND + 1)) + out="ci-${BUILD}-${slug:-${job_id:0:13}}.log" + # Retries share a name with the original job; disambiguate by uuid. + case "$EMITTED" in + *" $out "*) out="ci-${BUILD}-${slug:-job}-${job_id:0:13}.log" ;; + esac + EMITTED="${EMITTED}${out} " + if [ -e "$out" ] && [ -z "${CI_FETCH_LOG_FORCE:-}" ]; then + echo "Keeping existing ${out} (set CI_FETCH_LOG_FORCE=1 to refetch)." >&2 + elif ! fetch_job "$job_id" "$out"; then + echo "Failed to download log for job ${job_id} (${name})." >&2 + continue + fi + printf '%s\t%s\n' "$out" "$name" +done < <(awk -F'\t' "$FILTER" "$JOBS_TSV") -echo "$OUT" +if [ "$FOUND" -eq 0 ]; then + echo "No matching jobs in build ${BUILD} (scope: ${SCOPE})." >&2 +fi diff --git a/.buildkite/scripts/hardware_ci/run-intel-ci-test.sh b/.buildkite/scripts/hardware_ci/run-intel-ci-test.sh new file mode 100644 index 000000000000..d83a7bc4a13f --- /dev/null +++ b/.buildkite/scripts/hardware_ci/run-intel-ci-test.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +set -euo pipefail + +test_suite="${1:-}" + +if [[ -z "${test_suite}" ]]; then + echo "Usage: $0 " >&2 + exit 1 +fi + +case "${test_suite}" in + example) + pip install tblib==3.1.0 + + python3 examples/basic/offline_inference/generate.py --model facebook/opt-125m --block-size 64 --enforce-eager + python3 examples/basic/offline_inference/generate.py --model facebook/opt-125m --block-size 64 -O3 -cc.cudagraph_mode=NONE + python3 examples/basic/offline_inference/generate.py --model facebook/opt-125m --block-size 64 --enforce-eager -tp 2 --distributed-executor-backend mp + python3 examples/basic/offline_inference/generate.py --model facebook/opt-125m --block-size 64 --enforce-eager --attention-backend=TRITON_ATTN + python3 examples/basic/offline_inference/generate.py --model facebook/opt-125m --block-size 64 --enforce-eager --quantization fp8 + python3 examples/basic/offline_inference/generate.py --model facebook/opt-125m --block-size 64 --enforce-eager --kv-cache-dtype fp8 + python3 examples/basic/offline_inference/generate.py --model nvidia/Llama-3.1-8B-Instruct-FP8 --block-size 64 --enforce-eager --quantization modelopt --kv-cache-dtype fp8 --attention-backend TRITON_ATTN --max-model-len 4096 + python3 examples/basic/offline_inference/generate.py --model superjob/Qwen3-4B-Instruct-2507-GPTQ-Int4 --block-size 64 --enforce-eager --max-model-len 8192 + python3 examples/basic/offline_inference/generate.py --model ibm-research/PowerMoE-3b --block-size 64 --enforce-eager -tp 2 + python3 examples/basic/offline_inference/generate.py --model ibm-research/PowerMoE-3b --block-size 64 --enforce-eager -tp 2 --enable-expert-parallel + python3 examples/basic/offline_inference/generate.py --model superjob/Qwen3-4B-Instruct-2507-GPTQ-Int4 --max-model-len 8192 + ;; + v1) + cd tests + + pytest -v -s v1/core --ignore=v1/core/test_reset_prefix_cache_e2e.py --ignore=v1/core/test_scheduler_e2e.py + pytest -v -s v1/engine --ignore=v1/engine/test_output_processor.py + pytest -v -s v1/sample --ignore=v1/sample/test_logprobs.py --ignore=v1/sample/test_logprobs_e2e.py -k "not test_topk_only and not test_topp_only and not test_topk_and_topp" + pytest -v -s v1/worker --ignore=v1/worker/test_gpu_model_runner.py --ignore=v1/worker/test_worker_memory_snapshot.py + pytest -v -s v1/structured_output + pytest -v -s v1/test_serial_utils.py + pytest -v -s v1/spec_decode --ignore=v1/spec_decode/test_max_len.py --ignore=v1/spec_decode/test_speculators_eagle3.py --ignore=v1/spec_decode/test_acceptance_length.py + pytest -v -s v1/kv_connector/unit --ignore=v1/kv_connector/unit/test_multi_connector.py --ignore=v1/kv_connector/unit/test_example_connector.py --ignore=v1/kv_connector/unit/test_lmcache_integration.py --ignore=v1/kv_connector/unit/test_hf3fs_client.py --ignore=v1/kv_connector/unit/test_hf3fs_connector.py --ignore=v1/kv_connector/unit/test_hf3fs_metadata_server.py --ignore=v1/kv_connector/unit/test_offloading_connector.py + ;; + server) + pip install av + cd tests + + pytest -v -s entrypoints/multimodal/openai/chat_completion/test_audio_in_video.py + pytest -v -s benchmarks/test_serve_cli.py + ;; + *) + echo "Unknown Intel test suite: ${test_suite}" >&2 + exit 1 + ;; +esac diff --git a/.buildkite/scripts/hardware_ci/run-intel-test.sh b/.buildkite/scripts/hardware_ci/run-intel-test.sh index 0eb93f5a6b3e..246ea7de50e2 100755 --- a/.buildkite/scripts/hardware_ci/run-intel-test.sh +++ b/.buildkite/scripts/hardware_ci/run-intel-test.sh @@ -243,8 +243,10 @@ container_name="xpu_${BUILDKITE_COMMIT}_$(tr -dc A-Za-z0-9 < /dev/urandom | head # ---- Command source selection ---- commands="" +commands_source="" if [[ -n "${VLLM_TEST_COMMANDS:-}" ]]; then commands="${VLLM_TEST_COMMANDS}" + commands_source="env" echo "Commands sourced from VLLM_TEST_COMMANDS (quoting preserved)" elif [[ $# -gt 0 ]]; then all_yaml=true @@ -303,8 +305,12 @@ if [[ -z "$commands" ]]; then fi echo "Raw commands: $commands" -commands=$(re_quote_pytest_markers "$commands") -echo "After re-quoting: $commands" +if [[ "$commands_source" != "env" ]]; then + commands=$(re_quote_pytest_markers "$commands") + echo "After re-quoting: $commands" +else + echo "Skipping re-quoting for VLLM_TEST_COMMANDS input" +fi commands=$(apply_intel_test_overrides "$commands") echo "Final commands: $commands" diff --git a/.buildkite/test-amd.yaml b/.buildkite/test-amd.yaml index 148aea73c7fb..e8c2d57fd979 100644 --- a/.buildkite/test-amd.yaml +++ b/.buildkite/test-amd.yaml @@ -608,6 +608,11 @@ steps: - pytest -v -s plugins_tests/test_bge_m3_sparse_io_processor_plugins.py - pip uninstall bge_m3_sparse_plugin -y # END: `bge_m3_sparse io_processor` test + # BEGIN: `colbert_query io_processor` test + - pip install -e ./plugins/colbert_query_plugin + - pytest -v -s plugins_tests/test_colbert_query_io_processor_plugins.py + - pip uninstall colbert_query_plugin -y + # END: `colbert_query io_processor` test # BEGIN: `stat_logger` plugins test - pip install -e ./plugins/vllm_add_dummy_stat_logger - pytest -v -s plugins_tests/test_stats_logger_plugins.py @@ -1778,10 +1783,9 @@ steps: - tests/models/multimodal/generation - tests/models/multimodal/test_mapping.py commands: - - uv pip install --system --no-build-isolation 'git+https://github.com/AndreasKaratzas/mamba@rocm-7.0-v2.3.0' - - uv pip install --system --no-build-isolation 'git+https://github.com/Dao-AILab/causal-conv1d@v1.6.0' - - pytest -v -s models/language/generation -m hybrid_model --num-shards=$$BUILDKITE_PARALLEL_JOB_COUNT --shard-id=$$BUILDKITE_PARALLEL_JOB - + - pip install git+https://github.com/TIGER-AI-Lab/Mantis.git + - pytest -v -s models/multimodal/generation -m 'not core_model' --ignore models/multimodal/generation/test_common.py + - pytest -v -s models/multimodal/test_mapping.py - label: Multi-Modal Models (Extended Generation 2) # TBD timeout_in_minutes: 180 @@ -1793,9 +1797,8 @@ steps: - vllm/ - tests/models/multimodal/generation commands: - - uv pip install --system --no-build-isolation 'git+https://github.com/AndreasKaratzas/mamba@rocm-7.0-v2.3.0' - - uv pip install --system --no-build-isolation 'git+https://github.com/Dao-AILab/causal-conv1d@v1.6.0' - - pytest -v -s models/language/generation -m '(not core_model) and (not hybrid_model)' + - pip install git+https://github.com/TIGER-AI-Lab/Mantis.git + - pytest -v -s models/multimodal/generation/test_common.py -m 'split(group=0) and not core_model' - label: Multi-Modal Models (Extended Generation 3) # TBD @@ -2754,7 +2757,7 @@ steps: - vllm/_aiter_ops.py - vllm/platforms/rocm.py commands: - - python3 benchmarks/attention_benchmarks/benchmark.py --backends ROCM_ATTN ROCM_AITER_FA ROCM_AITER_UNIFIED_ATTN --batch-specs "8q1s1k" --repeats 1 --warmup-iters 1 + - python3 benchmarks/attention_benchmarks/benchmark.py --backends ROCM_ATTN ROCM_AITER_FA ROCM_AITER_UNIFIED_ATTN --batch-specs "8q1s1k" #-------------------------------------------------------- mi355 · distributed --------------------------------------------------------# diff --git a/.buildkite/test_areas/benchmarks.yaml b/.buildkite/test_areas/benchmarks.yaml index 85f804780179..1a02d7c57026 100644 --- a/.buildkite/test_areas/benchmarks.yaml +++ b/.buildkite/test_areas/benchmarks.yaml @@ -23,4 +23,4 @@ steps: - benchmarks/attention_benchmarks/ - vllm/v1/attention/ commands: - - python3 benchmarks/attention_benchmarks/benchmark.py --backends flash flashinfer --batch-specs "8q1s1k" --repeats 1 --warmup-iters 1 + - python3 benchmarks/attention_benchmarks/benchmark.py --backends flash flashinfer --batch-specs "8q1s1k" diff --git a/.buildkite/test_areas/misc.yaml b/.buildkite/test_areas/misc.yaml index cda2bb4dafe3..67fecf06df3d 100644 --- a/.buildkite/test_areas/misc.yaml +++ b/.buildkite/test_areas/misc.yaml @@ -138,11 +138,26 @@ steps: - vllm/v1/spec_decode/extract_hidden_states.py - vllm/model_executor/models/extract_hidden_states.py - vllm/transformers_utils/configs/extract_hidden_states.py + - vllm/distributed/kv_transfer/kv_connector/v1/example_hidden_states_connector.py - tests/v1/kv_connector/extract_hidden_states_integration commands: - export VLLM_WORKER_MULTIPROC_METHOD=spawn - pytest -v -s v1/kv_connector/extract_hidden_states_integration +- label: Extract Hidden States Integration (2 GPUs) + key: extract-hidden-states-integration-2-gpus + timeout_in_minutes: 20 + num_devices: 2 + source_file_dependencies: + - vllm/v1/spec_decode/extract_hidden_states.py + - vllm/model_executor/models/extract_hidden_states.py + - vllm/transformers_utils/configs/extract_hidden_states.py + - vllm/distributed/kv_transfer/kv_connector/v1/example_hidden_states_connector.py + - tests/v1/kv_connector/extract_hidden_states_integration + commands: + - export VLLM_WORKER_MULTIPROC_METHOD=spawn + - pytest -v -s -m 'distributed' v1/kv_connector/extract_hidden_states_integration + - label: Regression key: regression timeout_in_minutes: 20 diff --git a/.buildkite/test_areas/models_multimodal.yaml b/.buildkite/test_areas/models_multimodal.yaml index 48d24708358b..a7358e8dbd67 100644 --- a/.buildkite/test_areas/models_multimodal.yaml +++ b/.buildkite/test_areas/models_multimodal.yaml @@ -30,7 +30,6 @@ steps: - pip install git+https://github.com/TIGER-AI-Lab/Mantis.git - pytest -v -s models/multimodal/generation/test_common.py -m core_model -k "qwen3 or gemma" - pytest -v -s models/multimodal/generation/test_qwen2_5_vl.py -m core_model - - pytest -v -s models/multimodal/generation/test_vit_cudagraph.py -m core_model mirror: amd: device: mi325_1 @@ -63,9 +62,16 @@ steps: - tests/models/multimodal commands: - pip install git+https://github.com/TIGER-AI-Lab/Mantis.git - - pytest -v -s models/multimodal -m core_model --ignore models/multimodal/generation/test_common.py --ignore models/multimodal/generation/test_ultravox.py --ignore models/multimodal/generation/test_qwen2_5_vl.py --ignore models/multimodal/generation/test_qwen2_vl.py --ignore models/multimodal/generation/test_whisper.py --ignore models/multimodal/generation/test_memory_leak.py --ignore models/multimodal/processing + - pytest -v -s models/multimodal -m core_model --ignore models/multimodal/generation/test_common.py --ignore models/multimodal/generation/test_ultravox.py --ignore models/multimodal/generation/test_qwen2_5_vl.py --ignore models/multimodal/generation/test_qwen2_vl.py --ignore models/multimodal/generation/test_whisper.py --ignore models/multimodal/generation/test_memory_leak.py --ignore models/multimodal/generation/test_vit_cudagraph.py --ignore models/multimodal/processing + - pytest -v -s models/multimodal/generation/test_vit_cudagraph.py -m core_model - pytest models/multimodal/generation/test_memory_leak.py -m core_model - cd .. && VLLM_WORKER_MULTIPROC_METHOD=spawn pytest -v -s tests/models/multimodal/generation/test_whisper.py -m core_model # Otherwise, mp_method="spawn" doesn't work + mirror: + amd: + soft_fail: true + device: mi325_1 + depends_on: + - image-build-amd - label: Multi-Modal Processor (CPU) key: multi-modal-processor-cpu diff --git a/.buildkite/test_areas/plugins.yaml b/.buildkite/test_areas/plugins.yaml index 591afd946d23..310c2a8fd2a8 100644 --- a/.buildkite/test_areas/plugins.yaml +++ b/.buildkite/test_areas/plugins.yaml @@ -27,6 +27,10 @@ steps: - pip install -e ./plugins/bge_m3_sparse_plugin - pytest -v -s plugins_tests/test_bge_m3_sparse_io_processor_plugins.py - pip uninstall bge_m3_sparse_plugin -y + # test colbert_query io_processor plugin + - pip install -e ./plugins/colbert_query_plugin + - pytest -v -s plugins_tests/test_colbert_query_io_processor_plugins.py + - pip uninstall colbert_query_plugin -y # end io_processor plugins test # begin stat_logger plugins test - pip install -e ./plugins/vllm_add_dummy_stat_logger @@ -40,3 +44,17 @@ steps: - pytest -v -s plugins_tests/test_oot_registration_online.py # it needs a clean process - pytest -v -s plugins_tests/test_oot_registration_offline.py # it needs a clean process - pytest -v -s plugins_tests/lora_resolvers # unit tests for in-tree lora resolver plugins + + +- label: GGUF Plugin + key: gguf-plugin + device: h200_18gb + timeout_in_minutes: 30 + soft_fail: true + optional: true + source_file_dependencies: + - vllm/model_executor/layers/quantization + - tests/plugins_tests/test_gguf_plugin.py + commands: + - pip install "vllm-gguf-plugin >= 0.0.2" + - pytest -v -s plugins_tests/gguf diff --git a/.buildkite/test_areas/quantization.yaml b/.buildkite/test_areas/quantization.yaml index 8a9a36da4481..a92ee24f4aac 100644 --- a/.buildkite/test_areas/quantization.yaml +++ b/.buildkite/test_areas/quantization.yaml @@ -21,6 +21,18 @@ steps: - uv pip install --system conch-triton-kernels - VLLM_TEST_FORCE_LOAD_FORMAT=auto pytest -v -s quantization/ --ignore quantization/test_blackwell_moe.py +- label: Quantized Fusions + key: quantized-fusions + timeout_in_minutes: 30 + source_file_dependencies: + - tests/fusion + - vllm/model_executor/layers/fusion + - vllm/model_executor/kernels/linear + - vllm/model_executor/layers/quantization/compressed_tensors + - vllm/model_executor/layers/quantization/modelopt.py + commands: + - pytest -v -s fusion/ + - label: Quantized MoE Test (B200) key: quantized-moe-test-b200 timeout_in_minutes: 60 diff --git a/.buildkite/test_areas/rust_frontend.yaml b/.buildkite/test_areas/rust_frontend.yaml index 16d69f773450..f9abac2004e6 100644 --- a/.buildkite/test_areas/rust_frontend.yaml +++ b/.buildkite/test_areas/rust_frontend.yaml @@ -99,9 +99,13 @@ steps: - vllm/v1/engine/ - vllm/v1/worker/ - tests/utils.py + - tests/v1/distributed/test_external_lb_dp.py + - tests/v1/distributed/test_hybrid_lb_dp.py - tests/v1/distributed/test_internal_lb_dp.py commands: - export VLLM_USE_RUST_FRONTEND=1 - export VLLM_WORKER_MULTIPROC_METHOD=spawn - export NCCL_CUMEM_HOST_ENABLE=0 - TP_SIZE=1 DP_SIZE=4 pytest -v -s v1/distributed/test_internal_lb_dp.py -k "not 4 and not server_info" + - TP_SIZE=1 DP_SIZE=2 pytest -v -s v1/distributed/test_external_lb_dp.py -k "not 4 and not server_info" + - TP_SIZE=1 DP_SIZE=4 pytest -v -s v1/distributed/test_hybrid_lb_dp.py -k "not 4 and not server_info" diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 000000000000..940c28858094 --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,5 @@ +# Custom self-hosted runner labels (e.g. the autoscaling vllm-runners pool) so +# actionlint doesn't flag them as unknown in `runs-on`. +self-hosted-runner: + labels: + - vllm-runners diff --git a/.github/dependabot.yml b/.github/dependabot.yml index a017d69be991..944929fc55e5 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -21,7 +21,6 @@ updates: - dependency-name: "torchvision" - dependency-name: "xformers" - dependency-name: "lm-format-enforcer" - - dependency-name: "gguf" - dependency-name: "compressed-tensors" - dependency-name: "ray[cgraph]" # Ray Compiled Graph - dependency-name: "lm-eval" diff --git a/.github/mergify.yml b/.github/mergify.yml index f607da3178ca..4333c6e646da 100644 --- a/.github/mergify.yml +++ b/.github/mergify.yml @@ -388,9 +388,13 @@ pull_request_rules: - or: - files~=^tests/tool_use/ - files~=^tests/tool_parsers/ + - files~=^tests/parser/ + - files~=^tests/reasoning/ - files~=^tests/entrypoints/openai/.*tool.* - files~=^tests/entrypoints/anthropic/.*tool.* - files~=^vllm/tool_parsers/ + - files~=^vllm/parser/ + - files~=^vllm/reasoning/ - files=docs/features/tool_calling.md - files~=^examples/tool_calling/ actions: diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 93a5a5ff0ae3..2f3e3e6e52e0 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -46,12 +46,16 @@ jobs: pre-commit: needs: pre-run-check if: always() && (needs.pre-run-check.result == 'success' || needs.pre-run-check.result == 'skipped') - runs-on: ubuntu-latest + runs-on: [self-hosted, linux, x64, vllm-runners] steps: - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 - uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0 with: python-version: "3.12" + # Provide shellcheck on PATH so tools/pre_commit/shellcheck.sh skips its + # wget + tar -xJ self-download, which the self-hosted runner image lacks + # (no wget/xz). Pinned to shellcheck 0.10.0 to match the script's "stable". + - run: python -m pip install shellcheck-py==0.10.0.1 - run: echo "::add-matcher::.github/workflows/matchers/actionlint.json" - run: echo "::add-matcher::.github/workflows/matchers/markdownlint.json" - run: echo "::add-matcher::.github/workflows/matchers/mypy.json" diff --git a/.github/workflows/scripts/build.sh b/.github/workflows/scripts/build.sh index eb3971c42bfc..335ec735e62c 100644 --- a/.github/workflows/scripts/build.sh +++ b/.github/workflows/scripts/build.sh @@ -9,7 +9,7 @@ PATH=${cuda_home}/bin:$PATH LD_LIBRARY_PATH=${cuda_home}/lib64:$LD_LIBRARY_PATH # Install requirements -if [ "$(echo $2 | cut -d. -f1)" = "12" ]; then +if [ "$(echo "$2" | cut -d. -f1)" = "12" ]; then sed -i 's/^nvidia-cutlass-dsl\[cu13\]>=/nvidia-cutlass-dsl>=/' requirements/cuda.txt fi $python_executable -m pip install -r requirements/build/cuda.txt -r requirements/cuda.txt @@ -17,7 +17,10 @@ $python_executable -m pip install -r requirements/build/cuda.txt -r requirements # Limit the number of parallel jobs to avoid OOM export MAX_JOBS=1 # Make sure release wheels are built for the following architectures -export TORCH_CUDA_ARCH_LIST="7.5 8.0 8.6 8.9 9.0 10.0 12.0+PTX" +# Do not add +PTX here: vLLM filters torch's top-level PTX flag when it +# converts global gencode flags into per-kernel arch lists. If a specific +# kernel needs PTX, add +PTX to that kernel's CMake arch list instead. +export TORCH_CUDA_ARCH_LIST="7.5 8.0 8.6 8.9 9.0 10.0 12.0" bash tools/check_repo.sh diff --git a/.gitignore b/.gitignore index 8dde75e43e4b..c70200ed0914 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,9 @@ vllm/third_party/flashmla/flash_mla_interface.py # DeepGEMM vendored package built from source vllm/third_party/deep_gemm/ +# fmha_sm100 vendored package built from source +vllm/third_party/fmha_sm100/ + # triton jit .triton diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d0c83833a625..0b97a7c93ea6 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -21,7 +21,7 @@ repos: rev: v21.1.2 hooks: - id: clang-format - exclude: 'csrc/(libtorch_stable/moe/topk_softmax_kernels.cu|libtorch_stable/quantization/gguf/(ggml-common.h|dequantize.cuh|vecdotq.cuh|mmq.cuh|mmvq.cuh))|vllm/third_party/.*' + exclude: 'csrc/libtorch_stable/moe/topk_softmax_kernels.cu|vllm/third_party/.*' types_or: [c++, cuda] args: [--style=file, --verbose] - repo: https://github.com/DavidAnson/markdownlint-cli2 diff --git a/AGENTS.md b/AGENTS.md index 441b8d9fb739..1f3a083f80c1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -105,6 +105,26 @@ The line length limit for Python code is 88 characters. If you are not sure, use Use [Google-style docstrings](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) (`Args:`/`Returns:`/`Raises:` sections), not reStructuredText/Sphinx fields (`:param:`, `:return:`, `:rtype:`). +### Coding style guidelines + +Follow these rules for all code changes in this repository: + +- Try to match existing code style. +- Code should be self-documenting and self-explanatory. +- Keep comments and docstrings minimal and concise. +- Assume the reader is familiar with vLLM. + +### Diagnosing CI failures + +Buildkite logs are public; no login needed. Details: [docs/contributing/ci/failures.md](docs/contributing/ci/failures.md). + +```bash +# All failed-job logs for a PR's latest build (current branch's PR if omitted): +.buildkite/scripts/ci-fetch-log.sh --pr +# Any Buildkite build or job URL also works: +.buildkite/scripts/ci-fetch-log.sh "" +``` + ### Commit messages Add attribution using commit trailers such as `Co-authored-by:` (other projects use `Assisted-by:` or `Generated-by:`). For example: diff --git a/CMakeLists.txt b/CMakeLists.txt index c03360a5d4e3..1259ec0c1bf7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -190,6 +190,11 @@ if(VLLM_GPU_LANG STREQUAL "CUDA") # the set of architectures we want to compile for and remove the from the # CMAKE_CUDA_FLAGS so that they are not applied globally. # + # `+PTX` in TORCH_CUDA_ARCH_LIST is not preserved here. It is emitted by torch + # as `code=compute_*`, while extract_unique_cuda_archs_ascending() records only + # `arch=compute_*`. If a kernel really needs PTX, add `+PTX` to that kernel's + # component-specific arch list below. + # clear_cuda_arches(CUDA_ARCH_FLAGS) extract_unique_cuda_archs_ascending(CUDA_ARCHS "${CUDA_ARCH_FLAGS}") message(STATUS "CUDA target architectures: ${CUDA_ARCHS}") @@ -365,13 +370,13 @@ if(VLLM_GPU_LANG STREQUAL "CUDA") cuda_archs_loose_intersection(ES_MXFP8_GROUPED_MM_ARCHS "10.0a;10.1a;10.3a" "${CUDA_ARCHS}") endif() if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.8 AND ES_MXFP8_GROUPED_MM_ARCHS) - set(SRCS + set(ES_MXFP8_GROUPED_MM_SRCS "csrc/libtorch_stable/moe/mxfp8_moe/cutlass_mxfp8_grouped_mm.cu" "csrc/libtorch_stable/moe/mxfp8_moe/mxfp8_experts_quant.cu") set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${ES_MXFP8_GROUPED_MM_SRCS}" CUDA_ARCHS "${ES_MXFP8_GROUPED_MM_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${ES_MXFP8_GROUPED_MM_SRCS}") list(APPEND VLLM_GPU_FLAGS "-DENABLE_ES_MXFP8_GROUPED_MM_SM100=1") message(STATUS "Building ES MXFP8 grouped kernels for archs: ${ES_MXFP8_GROUPED_MM_ARCHS}") else() @@ -385,76 +390,6 @@ if(VLLM_GPU_LANG STREQUAL "CUDA") endif() endif() - # - # Machete kernels - - # The machete kernels only work on hopper and require CUDA 12.0 or later. - # Only build Machete kernels if we are building for something compatible with sm90a - cuda_archs_loose_intersection(MACHETE_ARCHS "9.0a" "${CUDA_ARCHS}") - if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.0 AND MACHETE_ARCHS) - # - # For the Machete kernels we automatically generate sources for various - # preselected input type pairs and schedules. - # Generate sources: - set(MACHETE_GEN_SCRIPT - ${CMAKE_CURRENT_SOURCE_DIR}/csrc/quantization/machete/generate.py) - file(MD5 ${MACHETE_GEN_SCRIPT} MACHETE_GEN_SCRIPT_HASH) - - message(STATUS "Machete generation script hash: ${MACHETE_GEN_SCRIPT_HASH}") - message(STATUS "Last run machete generate script hash: $CACHE{MACHETE_GEN_SCRIPT_HASH}") - - if (NOT DEFINED CACHE{MACHETE_GEN_SCRIPT_HASH} - OR NOT $CACHE{MACHETE_GEN_SCRIPT_HASH} STREQUAL ${MACHETE_GEN_SCRIPT_HASH}) - execute_process( - COMMAND ${CMAKE_COMMAND} -E env - PYTHONPATH=${CMAKE_CURRENT_SOURCE_DIR}/csrc/cutlass_extensions/:${CUTLASS_DIR}/python/:${VLLM_PYTHON_PATH}:$ENV{PYTHONPATH} - ${Python_EXECUTABLE} ${MACHETE_GEN_SCRIPT} - RESULT_VARIABLE machete_generation_result - OUTPUT_VARIABLE machete_generation_output - OUTPUT_FILE ${CMAKE_CURRENT_BINARY_DIR}/machete_generation.log - ERROR_FILE ${CMAKE_CURRENT_BINARY_DIR}/machete_generation.log - ) - - if (NOT machete_generation_result EQUAL 0) - message(FATAL_ERROR "Machete generation failed." - " Result: \"${machete_generation_result}\"" - "\nCheck the log for details: " - "${CMAKE_CURRENT_BINARY_DIR}/machete_generation.log") - else() - set(MACHETE_GEN_SCRIPT_HASH ${MACHETE_GEN_SCRIPT_HASH} - CACHE STRING "Last run machete generate script hash" FORCE) - message(STATUS "Machete generation completed successfully.") - endif() - else() - message(STATUS "Machete generation script has not changed, skipping generation.") - endif() - - # Add machete generated sources - file(GLOB MACHETE_GEN_SOURCES "csrc/quantization/machete/generated/*.cu") - list(APPEND VLLM_EXT_SRC ${MACHETE_GEN_SOURCES}) - - # forward compatible - set_gencode_flags_for_srcs( - SRCS "${MACHETE_GEN_SOURCES}" - CUDA_ARCHS "${MACHETE_ARCHS}") - - list(APPEND VLLM_EXT_SRC - csrc/quantization/machete/machete_pytorch.cu) - - message(STATUS "Building Machete kernels for archs: ${MACHETE_ARCHS}") - else() - if (NOT ${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.0 - AND MACHETE_ARCHS) - message(STATUS "Not building Machete kernels as CUDA Compiler version is " - "not >= 12.0, we recommend upgrading to CUDA 12.0 or " - "later if you intend on running w4a16 quantized models on " - "Hopper.") - else() - message(STATUS "Not building Machete kernels as no compatible archs " - "found in CUDA target architectures") - endif() - endif() - # if CUDA endif @@ -503,9 +438,9 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") "csrc/libtorch_stable/quantization/w8a8/int8/per_token_group_quant.cu" "csrc/libtorch_stable/permute_cols.cu" "csrc/libtorch_stable/quantization/gptq/q_gemm.cu" - "csrc/libtorch_stable/quantization/gguf/gguf_kernel.cu" "csrc/libtorch_stable/pos_encoding_kernels.cu" "csrc/libtorch_stable/fused_qknorm_rope_kernel.cu" + "csrc/libtorch_stable/fused_minimax_m3_qknorm_rope_kv_insert_kernel.cu" "csrc/libtorch_stable/layernorm_kernels.cu" "csrc/libtorch_stable/layernorm_quant_kernels.cu" "csrc/libtorch_stable/quantization/fused_kernels/fused_layernorm_dynamic_per_token_quant.cu" @@ -533,6 +468,75 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") "csrc/libtorch_stable/quantization/awq/gemm_kernels.cu" "csrc/libtorch_stable/minimax_reduce_rms_kernel.cu") + # + # Machete kernels + # + # The machete kernels only work on hopper and require CUDA 12.0 or later. + # Only build Machete kernels if we are building for something compatible with sm90a + cuda_archs_loose_intersection(MACHETE_ARCHS "9.0a" "${CUDA_ARCHS}") + if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.0 AND MACHETE_ARCHS) + # + # For the Machete kernels we automatically generate sources for various + # preselected input type pairs and schedules. + # Generate sources: + set(MACHETE_GEN_SCRIPT + ${CMAKE_CURRENT_SOURCE_DIR}/csrc/libtorch_stable/quantization/machete/generate.py) + file(MD5 ${MACHETE_GEN_SCRIPT} MACHETE_GEN_SCRIPT_HASH) + + message(STATUS "Machete generation script hash: ${MACHETE_GEN_SCRIPT_HASH}") + message(STATUS "Last run machete generate script hash: $CACHE{MACHETE_GEN_SCRIPT_HASH}") + + if (NOT DEFINED CACHE{MACHETE_GEN_SCRIPT_HASH} + OR NOT $CACHE{MACHETE_GEN_SCRIPT_HASH} STREQUAL ${MACHETE_GEN_SCRIPT_HASH}) + execute_process( + COMMAND ${CMAKE_COMMAND} -E env + PYTHONPATH=${CMAKE_CURRENT_SOURCE_DIR}/csrc/cutlass_extensions/:${CUTLASS_DIR}/python/:${VLLM_PYTHON_PATH}:$ENV{PYTHONPATH} + ${Python_EXECUTABLE} ${MACHETE_GEN_SCRIPT} + RESULT_VARIABLE machete_generation_result + OUTPUT_VARIABLE machete_generation_output + OUTPUT_FILE ${CMAKE_CURRENT_BINARY_DIR}/machete_generation.log + ERROR_FILE ${CMAKE_CURRENT_BINARY_DIR}/machete_generation.log + ) + + if (NOT machete_generation_result EQUAL 0) + message(FATAL_ERROR "Machete generation failed." + " Result: \"${machete_generation_result}\"" + "\nCheck the log for details: " + "${CMAKE_CURRENT_BINARY_DIR}/machete_generation.log") + else() + set(MACHETE_GEN_SCRIPT_HASH ${MACHETE_GEN_SCRIPT_HASH} + CACHE STRING "Last run machete generate script hash" FORCE) + message(STATUS "Machete generation completed successfully.") + endif() + else() + message(STATUS "Machete generation script has not changed, skipping generation.") + endif() + + # Add machete generated sources + file(GLOB MACHETE_GEN_SOURCES "csrc/libtorch_stable/quantization/machete/generated/*.cu") + list(APPEND VLLM_STABLE_EXT_SRC ${MACHETE_GEN_SOURCES}) + + # forward compatible + set_gencode_flags_for_srcs( + SRCS "${MACHETE_GEN_SOURCES}" + CUDA_ARCHS "${MACHETE_ARCHS}") + + list(APPEND VLLM_STABLE_EXT_SRC + csrc/libtorch_stable/quantization/machete/machete_pytorch.cu) + message(STATUS "Building Machete kernels for archs: ${MACHETE_ARCHS}") + else() + if (NOT ${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.0 + AND MACHETE_ARCHS) + message(STATUS "Not building Machete kernels as CUDA Compiler version is " + "not >= 12.0, we recommend upgrading to CUDA 12.0 or " + "later if you intend on running w4a16 quantized models on " + "Hopper.") + else() + message(STATUS "Not building Machete kernels as no compatible archs " + "found in CUDA target architectures") + endif() + endif() + set_gencode_flags_for_srcs( SRCS "${VLLM_STABLE_EXT_SRC}" CUDA_ARCHS "${CUDA_ARCHS}") @@ -678,16 +682,16 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") # DeepSeek V3 fused A GEMM kernel (requires SM 9.0+, Hopper and later) if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 13.0) - cuda_archs_loose_intersection(DSV3_FUSED_A_GEMM_ARCHS "9.0a;10.0f;11.0f" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(DSV3_FUSED_A_GEMM_ARCHS "9.0a;10.0f;11.0f;12.0f" "${CUDA_ARCHS}") else() - cuda_archs_loose_intersection(DSV3_FUSED_A_GEMM_ARCHS "9.0a;10.0a;10.1a;10.3a" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(DSV3_FUSED_A_GEMM_ARCHS "9.0a;10.0a;10.1a;10.3a;12.0a;12.1a" "${CUDA_ARCHS}") endif() if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.0 AND DSV3_FUSED_A_GEMM_ARCHS) - set(SRCS "csrc/libtorch_stable/dsv3_fused_a_gemm.cu") + set(DSV3_FUSED_A_GEMM_SRCS "csrc/libtorch_stable/dsv3_fused_a_gemm.cu") set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${DSV3_FUSED_A_GEMM_SRCS}" CUDA_ARCHS "${DSV3_FUSED_A_GEMM_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${DSV3_FUSED_A_GEMM_SRCS}") message(STATUS "Building dsv3_fused_a_gemm for archs: ${DSV3_FUSED_A_GEMM_ARCHS}") else() message(STATUS "Not building dsv3_fused_a_gemm as no compatible archs found " @@ -697,13 +701,13 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") # FP32 router GEMM (H=3072, E=256, M<=32). Requires SM90+ and CUDA >= 12.0. cuda_archs_sm90plus(FP32_ROUTER_GEMM_ARCHS "${CUDA_ARCHS}") if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.0 AND FP32_ROUTER_GEMM_ARCHS) - set(SRCS + set(FP32_ROUTER_GEMM_SRCS "csrc/libtorch_stable/fp32_router_gemm_entry.cu" "csrc/libtorch_stable/fp32_router_gemm.cu") set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${FP32_ROUTER_GEMM_SRCS}" CUDA_ARCHS "${FP32_ROUTER_GEMM_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${FP32_ROUTER_GEMM_SRCS}") message(STATUS "Building fp32_router_gemm for archs: ${FP32_ROUTER_GEMM_ARCHS}") else() message(STATUS "Not building fp32_router_gemm as no compatible archs found " @@ -713,13 +717,13 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") # Only build AllSpark kernels if we are building for at least some compatible archs. cuda_archs_loose_intersection(ALLSPARK_ARCHS "8.0;8.6;8.7;8.9" "${CUDA_ARCHS}") if (ALLSPARK_ARCHS) - set(SRCS + set(ALLSPARK_SRCS "csrc/libtorch_stable/quantization/gptq_allspark/allspark_repack.cu" "csrc/libtorch_stable/quantization/gptq_allspark/allspark_qgemm_w8a16.cu") set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${ALLSPARK_SRCS}" CUDA_ARCHS "${ALLSPARK_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${ALLSPARK_SRCS}") message(STATUS "Building AllSpark kernels for archs: ${ALLSPARK_ARCHS}") else() message(STATUS "Not building AllSpark kernels as no compatible archs found" @@ -734,16 +738,16 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") # CUDA 12.0 or later cuda_archs_loose_intersection(SCALED_MM_ARCHS "9.0a;" "${CUDA_ARCHS}") if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.0 AND SCALED_MM_ARCHS) - set(SRCS + set(SCALED_MM_SM90_SRCS "csrc/libtorch_stable/quantization/w8a8/cutlass/scaled_mm_c3x_sm90.cu" "csrc/libtorch_stable/quantization/w8a8/cutlass/c3x/scaled_mm_sm90_fp8.cu" "csrc/libtorch_stable/quantization/w8a8/cutlass/c3x/scaled_mm_sm90_int8.cu" "csrc/libtorch_stable/quantization/w8a8/cutlass/c3x/scaled_mm_azp_sm90_int8.cu" "csrc/libtorch_stable/quantization/w8a8/cutlass/c3x/scaled_mm_blockwise_sm90_fp8.cu") set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${SCALED_MM_SM90_SRCS}" CUDA_ARCHS "${SCALED_MM_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${SCALED_MM_SM90_SRCS}") list(APPEND VLLM_GPU_FLAGS "-DENABLE_SCALED_MM_SM90=1") # Let scaled_mm_c2x know it doesn't need to build these arches list(APPEND SCALED_MM_3X_ARCHS "${SCALED_MM_ARCHS}") @@ -769,15 +773,15 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") cuda_archs_loose_intersection(SCALED_MM_ARCHS "12.0a;12.1a" "${CUDA_ARCHS}") endif() if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.8 AND SCALED_MM_ARCHS) - set(SRCS + set(SCALED_MM_SM120_SRCS "csrc/libtorch_stable/quantization/w8a8/cutlass/scaled_mm_c3x_sm120.cu" "csrc/libtorch_stable/quantization/w8a8/cutlass/c3x/scaled_mm_sm120_fp8.cu" "csrc/libtorch_stable/quantization/w8a8/cutlass/c3x/scaled_mm_blockwise_sm120_fp8.cu" ) set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${SCALED_MM_SM120_SRCS}" CUDA_ARCHS "${SCALED_MM_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${SCALED_MM_SM120_SRCS}") list(APPEND VLLM_GPU_FLAGS "-DENABLE_SCALED_MM_SM120=1") # Let scaled_mm_c2x know it doesn't need to build these arches list(APPEND SCALED_MM_3X_ARCHS "${SCALED_MM_ARCHS}") @@ -803,15 +807,15 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") cuda_archs_loose_intersection(SCALED_MM_ARCHS "10.0a;10.1a;10.3a" "${CUDA_ARCHS}") endif() if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.8 AND SCALED_MM_ARCHS) - set(SRCS + set(SCALED_MM_SM100_SRCS "csrc/libtorch_stable/quantization/w8a8/cutlass/scaled_mm_c3x_sm100.cu" "csrc/libtorch_stable/quantization/w8a8/cutlass/c3x/scaled_mm_sm100_fp8.cu" "csrc/libtorch_stable/quantization/w8a8/cutlass/c3x/scaled_mm_blockwise_sm100_fp8.cu" ) set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${SCALED_MM_SM100_SRCS}" CUDA_ARCHS "${SCALED_MM_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${SCALED_MM_SM100_SRCS}") list(APPEND VLLM_GPU_FLAGS "-DENABLE_SCALED_MM_SM100=1") # Let scaled_mm_c2x know it doesn't need to build these arches list(APPEND SCALED_MM_3X_ARCHS "${SCALED_MM_ARCHS}") @@ -837,11 +841,11 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") # subtract out the archs that are already built for 3x list(REMOVE_ITEM SCALED_MM_2X_ARCHS ${SCALED_MM_3X_ARCHS}) if (SCALED_MM_2X_ARCHS) - set(SRCS "csrc/libtorch_stable/quantization/w8a8/cutlass/scaled_mm_c2x.cu") + set(SCALED_MM_C2X_SRCS "csrc/libtorch_stable/quantization/w8a8/cutlass/scaled_mm_c2x.cu") set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${SCALED_MM_C2X_SRCS}" CUDA_ARCHS "${SCALED_MM_2X_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${SCALED_MM_C2X_SRCS}") list(APPEND VLLM_GPU_FLAGS "-DENABLE_SCALED_MM_C2X=1") message(STATUS "Building scaled_mm_c2x for archs: ${SCALED_MM_2X_ARCHS}") else() @@ -863,11 +867,11 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") # if it's possible to compile MoE kernels that use its output. cuda_archs_loose_intersection(SCALED_MM_ARCHS "9.0a" "${CUDA_ARCHS}") if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.3 AND SCALED_MM_ARCHS) - set(SRCS "csrc/libtorch_stable/quantization/w8a8/cutlass/moe/grouped_mm_c3x_sm90.cu") + set(CUTLASS_MOE_SM90_SRCS "csrc/libtorch_stable/quantization/w8a8/cutlass/moe/grouped_mm_c3x_sm90.cu") set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${CUTLASS_MOE_SM90_SRCS}" CUDA_ARCHS "${SCALED_MM_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${CUTLASS_MOE_SM90_SRCS}") list(APPEND VLLM_GPU_FLAGS "-DENABLE_CUTLASS_MOE_SM90=1") message(STATUS "Building grouped_mm_c3x for archs: ${SCALED_MM_ARCHS}") else() @@ -882,16 +886,16 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") endif() if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 13.0) - cuda_archs_loose_intersection(SCALED_MM_ARCHS "10.0f;11.0f" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(SCALED_MM_ARCHS "10.0f" "${CUDA_ARCHS}") else() - cuda_archs_loose_intersection(SCALED_MM_ARCHS "10.0a;10.1a;10.3a" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(SCALED_MM_ARCHS "10.0a;10.3a" "${CUDA_ARCHS}") endif() if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.8 AND SCALED_MM_ARCHS) - set(SRCS "csrc/libtorch_stable/quantization/w8a8/cutlass/moe/grouped_mm_c3x_sm100.cu") + set(CUTLASS_MOE_SM100_SRCS "csrc/libtorch_stable/quantization/w8a8/cutlass/moe/grouped_mm_c3x_sm100.cu") set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${CUTLASS_MOE_SM100_SRCS}" CUDA_ARCHS "${SCALED_MM_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${CUTLASS_MOE_SM100_SRCS}") list(APPEND VLLM_GPU_FLAGS "-DENABLE_CUTLASS_MOE_SM100=1") message(STATUS "Building grouped_mm_c3x for archs: ${SCALED_MM_ARCHS}") else() @@ -912,11 +916,11 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") cuda_archs_loose_intersection(CUTLASS_MOE_DATA_ARCHS "9.0a;10.0a;10.1a;10.3a;12.0a;12.1a" "${CUDA_ARCHS}") endif() if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.3 AND CUTLASS_MOE_DATA_ARCHS) - set(SRCS "csrc/libtorch_stable/quantization/w8a8/cutlass/moe/moe_data.cu") + set(CUTLASS_MOE_DATA_SRCS "csrc/libtorch_stable/quantization/w8a8/cutlass/moe/moe_data.cu") set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${CUTLASS_MOE_DATA_SRCS}" CUDA_ARCHS "${CUTLASS_MOE_DATA_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${CUTLASS_MOE_DATA_SRCS}") message(STATUS "Building moe_data for archs: ${CUTLASS_MOE_DATA_ARCHS}") else() if (NOT ${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.3 AND CUTLASS_MOE_DATA_ARCHS) @@ -933,71 +937,66 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") # FP4/NVFP4 kernels (moved from _C to _C_stable_libtorch) # - # The nvfp4_scaled_mm_sm120 kernels for Blackwell SM12x require - # CUDA 12.8 or later + # SM12x FP4 kernels. These share some generic NVFP4 quantization entry + # sources with the SM10x/11x block below; set_gencode_flags_for_srcs appends + # per-source flags, so shared files accumulate both SM12x and SM10x/11x + # gencodes when both families are requested. if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 13.0) - cuda_archs_loose_intersection(FP4_ARCHS "12.0f" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(FP4_SM120_ARCHS "12.0f" "${CUDA_ARCHS}") else() - cuda_archs_loose_intersection(FP4_ARCHS "12.0a;12.1a" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(FP4_SM120_ARCHS "12.0a;12.1a" "${CUDA_ARCHS}") endif() - if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.8 AND FP4_ARCHS) - set(SRCS + if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.8 AND FP4_SM120_ARCHS) + set(FP4_SM120_SRCS "csrc/libtorch_stable/quantization/fp4/nvfp4_quant_kernels.cu" "csrc/libtorch_stable/quantization/fp4/activation_nvfp4_quant_fusion_kernels.cu" "csrc/libtorch_stable/quantization/fp4/nvfp4_experts_quant.cu" "csrc/libtorch_stable/quantization/fp4/nvfp4_scaled_mm_sm120_kernels.cu" - "csrc/libtorch_stable/quantization/fp4/nvfp4_blockwise_moe_kernel.cu") - set_gencode_flags_for_srcs( - SRCS "${SRCS}" - CUDA_ARCHS "${FP4_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") - set(NVFP4_KV_SRC "csrc/libtorch_stable/nvfp4_kv_cache_kernels.cu") + "csrc/libtorch_stable/quantization/fp4/nvfp4_blockwise_moe_kernel.cu" + "csrc/libtorch_stable/nvfp4_kv_cache_kernels.cu") set_gencode_flags_for_srcs( - SRCS "${NVFP4_KV_SRC}" - CUDA_ARCHS "${FP4_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${NVFP4_KV_SRC}") + SRCS "${FP4_SM120_SRCS}" + CUDA_ARCHS "${FP4_SM120_ARCHS}") + list(APPEND VLLM_STABLE_EXT_SRC "${FP4_SM120_SRCS}") target_compile_definitions(_C PRIVATE ENABLE_NVFP4_SM120=1) list(APPEND VLLM_GPU_FLAGS "-DENABLE_NVFP4_SM120=1") list(APPEND VLLM_GPU_FLAGS "-DENABLE_CUTLASS_MOE_SM120=1") - message(STATUS "Building NVFP4 for archs: ${FP4_ARCHS}") + message(STATUS "Building SM12x NVFP4 for archs: ${FP4_SM120_ARCHS}") else() - message(STATUS "Not building NVFP4 as no compatible archs were found.") - # clear FP4_ARCHS - set(FP4_ARCHS) + message(STATUS "Not building SM12x NVFP4 as no compatible archs were found.") endif() - # FP4 Archs and flags + # SM10x/11x FP4 kernels. MXFP4 experts quantization is currently compiled + # only in this block; SM12x has separate NVFP4 matmul/MoE kernels above. if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 13.0) - cuda_archs_loose_intersection(FP4_ARCHS "10.0f;11.0f" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(FP4_SM100_ARCHS "10.0f;11.0f" "${CUDA_ARCHS}") else() - cuda_archs_loose_intersection(FP4_ARCHS "10.0a;10.1a;10.3a" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(FP4_SM100_ARCHS "10.0a;10.1a;10.3a" "${CUDA_ARCHS}") endif() - if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.8 AND FP4_ARCHS) - set(SRCS + if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.8 AND FP4_SM100_ARCHS) + set(FP4_SM100_SRCS "csrc/libtorch_stable/quantization/fp4/nvfp4_quant_kernels.cu" "csrc/libtorch_stable/quantization/fp4/activation_nvfp4_quant_fusion_kernels.cu" "csrc/libtorch_stable/quantization/fp4/nvfp4_experts_quant.cu" "csrc/libtorch_stable/quantization/fp4/nvfp4_scaled_mm_kernels.cu" "csrc/libtorch_stable/quantization/fp4/nvfp4_blockwise_moe_kernel.cu" "csrc/libtorch_stable/quantization/fp4/mxfp4_experts_quant.cu" - "csrc/libtorch_stable/quantization/fp4/mxfp4_blockwise_moe_kernel.cu") - set_gencode_flags_for_srcs( - SRCS "${SRCS}" - CUDA_ARCHS "${FP4_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") - set(NVFP4_KV_SRC "csrc/libtorch_stable/nvfp4_kv_cache_kernels.cu") + "csrc/libtorch_stable/quantization/fp4/mxfp4_blockwise_moe_kernel.cu" + "csrc/libtorch_stable/nvfp4_kv_cache_kernels.cu") + if(NOT ${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.9) + message(STATUS + "Building mxfp4_experts_quant unsupported stubs because CUDA compiler version is not >= 12.9 (found ${CMAKE_CUDA_COMPILER_VERSION}).") + endif() set_gencode_flags_for_srcs( - SRCS "${NVFP4_KV_SRC}" - CUDA_ARCHS "${FP4_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${NVFP4_KV_SRC}") + SRCS "${FP4_SM100_SRCS}" + CUDA_ARCHS "${FP4_SM100_ARCHS}") + list(APPEND VLLM_STABLE_EXT_SRC "${FP4_SM100_SRCS}") target_compile_definitions(_C PRIVATE ENABLE_NVFP4_SM100=1) list(APPEND VLLM_GPU_FLAGS "-DENABLE_NVFP4_SM100=1") list(APPEND VLLM_GPU_FLAGS "-DENABLE_CUTLASS_MOE_SM100=1") - message(STATUS "Building NVFP4 for archs: ${FP4_ARCHS}") + message(STATUS "Building SM10x/11x NVFP4/MXFP4 for archs: ${FP4_SM100_ARCHS}") else() - message(STATUS "Not building NVFP4 as no compatible archs were found.") - # clear FP4_ARCHS - set(FP4_ARCHS) + message(STATUS "Not building SM10x/11x NVFP4/MXFP4 as no compatible archs were found.") endif() # @@ -1007,17 +1006,17 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") # Only build W4A8 kernels if we are building for something compatible with sm90a cuda_archs_loose_intersection(W4A8_ARCHS "9.0a" "${CUDA_ARCHS}") if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.0 AND W4A8_ARCHS) - set(SRCS + set(W4A8_SRCS "csrc/libtorch_stable/quantization/cutlass_w4a8/w4a8_mm_entry.cu" "csrc/libtorch_stable/quantization/cutlass_w4a8/w4a8_grouped_mm_entry.cu" "csrc/libtorch_stable/quantization/cutlass_w4a8/w4a8_utils.cu" ) set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${W4A8_SRCS}" CUDA_ARCHS "${W4A8_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${W4A8_SRCS}") message(STATUS "Building W4A8 kernels for archs: ${W4A8_ARCHS}") else() @@ -1033,22 +1032,24 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") endif() endif() - # CUTLASS MLA Archs and flags + # CUTLASS MLA Archs and flags. + # Runtime dispatch is gated in + # vllm/v1/attention/backends/mla/cutlass_mla.py. if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 13.0) - cuda_archs_loose_intersection(MLA_ARCHS "10.0f;11.0f;12.0f" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(MLA_ARCHS "10.0f;11.0f" "${CUDA_ARCHS}") else() - cuda_archs_loose_intersection(MLA_ARCHS "10.0a;10.1a;10.3a;12.0a;12.1a" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(MLA_ARCHS "10.0a;10.1a;10.3a" "${CUDA_ARCHS}") endif() if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.8 AND MLA_ARCHS) - set(SRCS + set(CUTLASS_MLA_SRCS "csrc/libtorch_stable/attention/mla/sm100_cutlass_mla_kernel.cu") set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${CUTLASS_MLA_SRCS}" CUDA_ARCHS "${MLA_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${CUTLASS_MLA_SRCS}") list(APPEND VLLM_GPU_FLAGS "-DENABLE_CUTLASS_MLA=1") # Add MLA-specific include directories only to MLA source files - set_source_files_properties(${SRCS} + set_source_files_properties(${CUTLASS_MLA_SRCS} PROPERTIES INCLUDE_DIRECTORIES "${CUTLASS_DIR}/examples/77_blackwell_fmha;${CUTLASS_DIR}/examples/common") message(STATUS "Building CUTLASS MLA for archs: ${MLA_ARCHS}") else() @@ -1060,11 +1061,11 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") # Hadacore kernels cuda_archs_loose_intersection(HADACORE_ARCHS "8.0+PTX;9.0+PTX" "${CUDA_ARCHS}") if(HADACORE_ARCHS) - set(SRCS "csrc/libtorch_stable/quantization/hadamard/hadacore/hadamard_transform_cuda.cu") + set(HADACORE_SRCS "csrc/libtorch_stable/quantization/hadamard/hadacore/hadamard_transform_cuda.cu") set_gencode_flags_for_srcs( - SRCS "${SRCS}" + SRCS "${HADACORE_SRCS}" CUDA_ARCHS "${HADACORE_ARCHS}") - list(APPEND VLLM_STABLE_EXT_SRC "${SRCS}") + list(APPEND VLLM_STABLE_EXT_SRC "${HADACORE_SRCS}") message(STATUS "Building hadacore") endif() @@ -1072,6 +1073,7 @@ if(VLLM_GPU_LANG STREQUAL "CUDA" OR VLLM_GPU_LANG STREQUAL "HIP") endif() message(STATUS "Enabling C_stable extension.") + list(REMOVE_DUPLICATES VLLM_STABLE_EXT_SRC) define_extension_target( _C_stable_libtorch DESTINATION vllm @@ -1176,7 +1178,11 @@ if(VLLM_GPU_LANG STREQUAL "CUDA") # - sm80 doesn't support fp8 computation # - sm90 and sm100 don't support QMMA.16832.F32.E4M3.E4M3 SAAS instruction # so we only enable fp8 computation for SM89 (e.g. RTX 40x0) and 12.0 (e.g. RTX 50x0) - cuda_archs_loose_intersection(MARLIN_MOE_FP8_ARCHS "8.9;12.0;12.1" "${CUDA_ARCHS}") + if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 13.0) + cuda_archs_loose_intersection(MARLIN_MOE_FP8_ARCHS "8.9;12.0f" "${CUDA_ARCHS}") + else() + cuda_archs_loose_intersection(MARLIN_MOE_FP8_ARCHS "8.9;12.0a;12.1a" "${CUDA_ARCHS}") + endif() # moe marlin arches for other files cuda_archs_loose_intersection(MARLIN_MOE_OTHER_ARCHS "7.5;8.0+PTX" "${CUDA_ARCHS}") if (MARLIN_MOE_OTHER_ARCHS) @@ -1393,6 +1399,7 @@ endif() # For CUDA we also build and ship some external projects. if (VLLM_GPU_LANG STREQUAL "CUDA") include(cmake/external_projects/deepgemm.cmake) + include(cmake/external_projects/fmha_sm100.cmake) include(cmake/external_projects/flashmla.cmake) include(cmake/external_projects/qutlass.cmake) diff --git a/benchmarks/attention_benchmarks/README.md b/benchmarks/attention_benchmarks/README.md index afce34433167..944ceb91af91 100644 --- a/benchmarks/attention_benchmarks/README.md +++ b/benchmarks/attention_benchmarks/README.md @@ -108,7 +108,6 @@ python benchmark.py \ --backends flash triton flashinfer \ --batch-specs "q2k" "8q1s1k" "2q2k_32q1s1k" \ --num-layers 10 \ - --repeats 5 \ --output-csv results.csv ``` @@ -164,14 +163,17 @@ python benchmark.py \ # Model configuration --num-layers N # Number of layers --head-dim N # Head dimension +--v-head-dim N # Value head dimension (defaults to --head-dim) --num-q-heads N # Query heads --num-kv-heads N # KV heads --block-size N # Block size +--kv-lora-rank N # MLA KV LoRA rank +--qk-nope-head-dim N # MLA non-RoPE QK head dim +--qk-rope-head-dim N # MLA RoPE QK head dim # Benchmark settings --device DEVICE # Device (default: cuda:0) ---repeats N # Repetitions ---warmup-iters N # Warmup iterations +--warmup-ms N # Warmup window in ms for triton do_bench --profile-memory # Profile memory usage # Parameter sweeps @@ -211,8 +213,6 @@ config = BenchmarkConfig( num_kv_heads=1, block_size=128, device="cuda:0", - repeats=5, - warmup_iters=3, ) # CUTLASS MLA with specific num_kv_splits @@ -253,14 +253,10 @@ formatter.save_json(results, "output.json") ## Tips -**1. Warmup matters** - Use `--warmup-iters 10` for stable results +**1. Save results** - Always use `--output-csv` or `--output-json` -**2. Multiple repeats** - Use `--repeats 20` for low variance +**2. Test incrementally** - Start with `--num-layers 1` -**3. Save results** - Always use `--output-csv` or `--output-json` +**3. Extended grammar** - Leverage spec decode, chunked prefill patterns -**4. Test incrementally** - Start with `--num-layers 1 --repeats 1` - -**5. Extended grammar** - Leverage spec decode, chunked prefill patterns - -**6. Parameter sweeps** - Use `--sweep-param` and `--sweep-values` to find optimal values +**4. Parameter sweeps** - Use `--sweep-param` and `--sweep-values` to find optimal values diff --git a/benchmarks/attention_benchmarks/benchmark.py b/benchmarks/attention_benchmarks/benchmark.py index c4c331f7f8ef..9860d4b2d1c2 100644 --- a/benchmarks/attention_benchmarks/benchmark.py +++ b/benchmarks/attention_benchmarks/benchmark.py @@ -26,6 +26,9 @@ """ import argparse +import os +import shutil +import subprocess import sys from dataclasses import replace from pathlib import Path @@ -50,6 +53,16 @@ from vllm.v1.worker.workspace import init_workspace_manager +def _str2bool(v) -> bool: + if isinstance(v, bool): + return v + if v.lower() in ("true", "1", "yes", "t"): + return True + if v.lower() in ("false", "0", "no", "f"): + return False + raise argparse.ArgumentTypeError(f"expected a boolean, got {v!r}") + + def run_standard_attention_benchmark(config: BenchmarkConfig) -> BenchmarkResult: """Run standard attention benchmark (Flash/Triton/FlashInfer).""" from runner import run_attention_benchmark @@ -83,13 +96,15 @@ def run_benchmark(config: BenchmarkConfig, **kwargs) -> BenchmarkResult: else: return run_standard_attention_benchmark(config) except Exception as e: + error_msg = str(e) or repr(e) return BenchmarkResult( config=config, mean_time=float("inf"), + median_time=float("inf"), std_time=0, min_time=float("inf"), max_time=float("inf"), - error=str(e), + error=error_msg, ) @@ -115,9 +130,12 @@ def run_model_parameter_sweep( """ all_results = [] - console.print( - f"[yellow]Model sweep mode: testing {sweep.param_name} = {sweep.values}[/]" + sweep_desc = ( + f"{sweep.param_name} = {sweep.values}" + if sweep.param_name + else f"{len(sweep.values)} configurations" ) + console.print(f"[yellow]Model sweep mode: testing {sweep_desc}[/]") total = len(backends) * len(batch_specs) * len(sweep.values) @@ -125,9 +143,9 @@ def run_model_parameter_sweep( for backend in backends: for spec in batch_specs: for value in sweep.values: - # Create config with modified model parameter + # Create config with modified model parameter(s) config_args = base_config_args.copy() - config_args[sweep.param_name] = value + sweep.apply(config_args, value) # Create config with original backend for running clean_config = BenchmarkConfig( @@ -144,13 +162,21 @@ def run_model_parameter_sweep( all_results.append(result) if not result.success: + err_label = ( + f"{sweep.param_name}={value}" + if sweep.param_name + else f"{value}" + ) console.print( - f"[red]Error {backend} {spec} {sweep.param_name}=" - f"{value}: {result.error}[/]" + f"[red]Error {backend} {spec} {err_label}" + f": {result.error}[/]" ) pbar.update(1) + if base_config_args.get("ncu_profile"): + return all_results + # Display sweep results - create separate table for each parameter value console.print("\n[bold green]Model Parameter Sweep Results:[/]") formatter = ResultsFormatter(console) @@ -184,7 +210,10 @@ def run_model_parameter_sweep( ) for param_value in sorted_param_values: - console.print(f"\n[bold cyan]{sweep.param_name} = {param_value}[/]") + label = ( + f"{sweep.param_name} = {param_value}" if sweep.param_name else param_value + ) + console.print(f"\n[bold cyan]{label}[/]") param_results = by_param_value[param_value] # Create modified results with original backend names @@ -200,8 +229,9 @@ def run_model_parameter_sweep( formatter.print_table(modified_results, backends, compare_to_fastest=True) # Show optimal backend for each (param_value, batch_spec) combination + sweep_name = sweep.param_name or "config" console.print( - f"\n[bold cyan]Optimal backend for each ({sweep.param_name}, batch_spec):[/]" + f"\n[bold cyan]Optimal backend for each ({sweep_name}, batch_spec):[/]" ) # Group by (param_value, batch_spec) @@ -236,7 +266,10 @@ def run_model_parameter_sweep( for param_value, spec in sorted_keys: # Print header when param value changes if param_value != current_param_value: - console.print(f"\n [bold]{sweep.param_name}={param_value}:[/]") + header = ( + f"{sweep.param_name}={param_value}" if sweep.param_name else param_value + ) + console.print(f"\n [bold]{header}:[/]") current_param_value = param_value results = by_param_and_spec[(param_value, spec)] @@ -322,6 +355,9 @@ def run_parameter_sweep( pbar.update(1) + if base_config_args.get("ncu_profile"): + return all_results + # Display sweep results console.print("\n[bold green]Sweep Results:[/]") backend_labels = [sweep.get_label(b, v) for b in backends for v in sweep_values] @@ -459,6 +495,20 @@ def main(): help="Prefill backends to compare (fa2, fa3, fa4). " "Uses the first decode backend for impl construction.", ) + parser.add_argument( + "--fp8-output-scale", + type=float, + help="Static per-tensor scale enabling the MLA prefill FP8-output " + "comparison on FA4 (fused write vs standalone post-quant).", + ) + parser.add_argument( + "--fuse-quant-op", + nargs="+", + type=_str2bool, + help="FP8-output write path(s) to run: false = bf16 attention + " + "standalone static-FP8 quant, true = FA4 writes FP8 directly. " + "Default: both.", + ) # Batch specifications parser.add_argument( @@ -474,11 +524,35 @@ def main(): parser.add_argument("--num-q-heads", type=int, default=32, help="Query heads") parser.add_argument("--num-kv-heads", type=int, default=8, help="KV heads") parser.add_argument("--block-size", type=int, default=16, help="Block size") + parser.add_argument( + "--v-head-dim", + type=int, + default=None, + help="Value head dimension (defaults to --head-dim if unset)", + ) + + # MLA-specific model dimensions + parser.add_argument( + "--kv-lora-rank", type=int, default=None, help="MLA KV LoRA rank" + ) + parser.add_argument( + "--qk-nope-head-dim", type=int, default=None, help="MLA non-RoPE QK head dim" + ) + parser.add_argument( + "--qk-rope-head-dim", type=int, default=None, help="MLA RoPE QK head dim" + ) # Benchmark settings parser.add_argument("--device", default="cuda:0", help="Device") - parser.add_argument("--repeats", type=int, default=1, help="Repetitions") - parser.add_argument("--warmup-iters", type=int, default=3, help="Warmup iterations") + parser.add_argument( + "--warmup-ms", + type=int, + default=None, + help=( + "Warmup window in ms for triton's do_bench (default: triton's own). " + "Has no effect with CUDA graphs; pass --no-cuda-graphs to use it." + ), + ) parser.add_argument("--profile-memory", action="store_true", help="Profile memory") parser.add_argument( "--kv-cache-dtype", @@ -491,10 +565,33 @@ def main(): action=argparse.BooleanOptionalAction, default=True, help=( - "Launch kernels with CUDA graphs to eliminate CPU overhead" - "in measurements (default: True)" + "Use triton do_bench_cudagraph (True) or do_bench (False) " + "for timing. CUDA graphs eliminate CPU launch overhead " + "(default: True)" + ), + ) + parser.add_argument( + "--num-splits", + type=int, + default=None, + help="FlashAttention split-K factor (0=auto heuristic, 1=disabled, >1=force N)", + ) + parser.add_argument( + "--ncu-profile", + action="store_true", + default=False, + help=( + "Enable Nsight Compute profiling mode. Automatically wraps the " + "script with ncu, capturing a profile with source correlation. " + "Use --ncu-output to set the output file name." ), ) + parser.add_argument( + "--ncu-output", + type=str, + default="profile", + help="Output file name for ncu profile (default: 'profile').", + ) # Parameter sweep (use YAML config for advanced sweeps) parser.add_argument( @@ -545,6 +642,12 @@ def main(): # Prefill backends (e.g., ["fa3", "fa4"]) args.prefill_backends = yaml_config.get("prefill_backends", None) + # FP8 output benchmark knobs; CLI wins. + if args.fp8_output_scale is None: + args.fp8_output_scale = yaml_config.get("fp8_output_scale", None) + if args.fuse_quant_op is None: + args.fuse_quant_op = yaml_config.get("fuse_quant_op", None) + # Check for special modes args.mode = yaml_config.get("mode", None) @@ -576,23 +679,28 @@ def main(): model = yaml_config["model"] args.num_layers = model.get("num_layers", args.num_layers) args.head_dim = model.get("head_dim", args.head_dim) + args.v_head_dim = model.get("v_head_dim", args.v_head_dim) args.num_q_heads = model.get("num_q_heads", args.num_q_heads) args.num_kv_heads = model.get("num_kv_heads", args.num_kv_heads) args.block_size = model.get("block_size", args.block_size) + # MLA-specific dimensions + args.kv_lora_rank = model.get("kv_lora_rank", args.kv_lora_rank) + args.qk_nope_head_dim = model.get("qk_nope_head_dim", args.qk_nope_head_dim) + args.qk_rope_head_dim = model.get("qk_rope_head_dim", args.qk_rope_head_dim) # Benchmark settings (top-level keys) if "device" in yaml_config: args.device = yaml_config["device"] - if "repeats" in yaml_config: - args.repeats = yaml_config["repeats"] - if "warmup_iters" in yaml_config: - args.warmup_iters = yaml_config["warmup_iters"] + if "warmup_ms" in yaml_config: + args.warmup_ms = yaml_config["warmup_ms"] if "profile_memory" in yaml_config: args.profile_memory = yaml_config["profile_memory"] if "kv_cache_dtype" in yaml_config: args.kv_cache_dtype = yaml_config["kv_cache_dtype"] if "cuda_graphs" in yaml_config: args.cuda_graphs = yaml_config["cuda_graphs"] + if "ncu_profile" in yaml_config: + args.ncu_profile = yaml_config["ncu_profile"] # Parameter sweep configuration if "parameter_sweep" in yaml_config: @@ -612,7 +720,7 @@ def main(): if "model_parameter_sweep" in yaml_config: sweep_config = yaml_config["model_parameter_sweep"] args.model_parameter_sweep = ModelParameterSweep( - param_name=sweep_config["param_name"], + param_name=sweep_config.get("param_name"), values=sweep_config["values"], label_format=sweep_config.get( "label_format", "{backend}_{param_name}_{value}" @@ -631,6 +739,32 @@ def main(): console.print() + # Re-exec under ncu if --ncu-profile and not already inside ncu. This runs + # after YAML processing so ncu_profile set via config file is honored. + if args.ncu_profile and "_NCU_INNER" not in os.environ: + ncu = shutil.which("ncu") + if ncu is None: + print("Error: 'ncu' not found in PATH", file=sys.stderr) + sys.exit(1) + cmd = [ + ncu, + "--profile-from-start", + "off", + "--set", + "full", + "--import-source", + "yes", + "-o", + args.ncu_output, + sys.executable, + *sys.argv, + ] + env = os.environ.copy() + env["CUTE_DSL_LINEINFO"] = "1" + env["_NCU_INNER"] = "1" + print(f"Launching: {' '.join(cmd)}") + sys.exit(subprocess.call(cmd, env=env)) + # Handle CLI-based parameter sweep (if not from YAML) if ( (not hasattr(args, "parameter_sweep") or args.parameter_sweep is None) @@ -655,6 +789,18 @@ def main(): console.print(f"Batch specs: {', '.join(args.batch_specs)}") console.print(f"KV cache dtype: {args.kv_cache_dtype}") console.print(f"CUDA graphs: {args.cuda_graphs}") + if args.warmup_ms is not None and args.cuda_graphs: + console.print( + "[yellow]Warning: --warmup-ms is ignored with CUDA graphs " + "(do_bench_cudagraph warms up internally). Pass --no-cuda-graphs " + "to use it.[/]" + ) + if args.num_splits == 0 and args.cuda_graphs: + console.print( + "[yellow]Warning: --num-splits 0 (FA3 heuristic) is not CUDA-graph " + "compatible and may fail or fall back. Pass --no-cuda-graphs or use " + "--num-splits >=1.[/]" + ) console.print() init_workspace_manager(args.device) @@ -662,8 +808,68 @@ def main(): # Run benchmarks all_results = [] + # Under ncu profiling the kernels run only to be captured by the profiler; + # timings are placeholder zeros, so the result tables and saved metrics are + # skipped. The Nsight Compute report (--ncu-output) holds the real data. + if args.ncu_profile: + console.print( + "[dim]ncu profiling enabled: result tables and saved metrics are " + "skipped (timings are placeholder zeros).[/]" + ) + + # FA4 fused FP8 output vs standalone post-quant, on the same fa4 kernel: + # the delta is the post-quant kernel the fused path removes. + fp8_output_scale = getattr(args, "fp8_output_scale", None) + if fp8_output_scale is not None: + decode_backend = backends[0] + fuse_variants = args.fuse_quant_op or [False, True] + label_of = {False: "post_quant", True: "fused"} + console.print( + f"[yellow]FP8 output comparison @ scale={fp8_output_scale} " + f"(prefill=fa4, decode impl={decode_backend})[/]" + ) + fp8_results = [] + total = len(fuse_variants) * len(args.batch_specs) + with tqdm(total=total, desc="FP8 output benchmarking") as pbar: + for spec in args.batch_specs: + for fuse in fuse_variants: + config = BenchmarkConfig( + backend=decode_backend, + batch_spec=spec, + num_layers=args.num_layers, + head_dim=args.head_dim, + num_q_heads=args.num_q_heads, + num_kv_heads=args.num_kv_heads, + block_size=args.block_size, + device=args.device, + repeats=args.repeats, + warmup_iters=args.warmup_iters, + profile_memory=args.profile_memory, + kv_cache_dtype=args.kv_cache_dtype, + use_cuda_graphs=args.cuda_graphs, + prefill_backend="fa4", + ) + result = run_benchmark( + config, output_scale=fp8_output_scale, fuse_quant_op=fuse + ) + label = label_of[fuse] + labeled_config = replace(result.config, backend=label) + result = replace(result, config=labeled_config) + fp8_results.append(result) + + if not result.success: + console.print(f"[red]Error {label} {spec}: {result.error}[/]") + + pbar.update(1) + + console.print("\n[bold green]FP8 Output Results:[/]") + formatter = ResultsFormatter(console) + labels = [label_of[f] for f in fuse_variants] + formatter.print_table(fp8_results, labels, compare_to_fastest=True) + all_results = fp8_results + # Handle special mode: decode_vs_prefill comparison - if hasattr(args, "mode") and args.mode == "decode_vs_prefill": + elif hasattr(args, "mode") and args.mode == "decode_vs_prefill": console.print("[yellow]Mode: Decode vs Prefill pipeline comparison[/]") console.print( "[dim]For each query length, testing both decode and prefill pipelines[/]" @@ -708,11 +914,11 @@ def main(): num_kv_heads=args.num_kv_heads, block_size=args.block_size, device=args.device, - repeats=args.repeats, - warmup_iters=args.warmup_iters, profile_memory=args.profile_memory, kv_cache_dtype=args.kv_cache_dtype, use_cuda_graphs=args.cuda_graphs, + ncu_profile=args.ncu_profile, + warmup_ms=args.warmup_ms, ) # Add decode pipeline config @@ -749,6 +955,7 @@ def main(): result = BenchmarkResult( config=config, mean_time=timing["mean"], + median_time=timing.get("median", timing["mean"]), std_time=timing["std"], min_time=timing["min"], max_time=timing["max"], @@ -770,6 +977,7 @@ def main(): result = BenchmarkResult( config=config, mean_time=float("inf"), + median_time=float("inf"), std_time=0, min_time=float("inf"), max_time=float("inf"), @@ -779,6 +987,9 @@ def main(): pbar.update(1) + if args.ncu_profile: + return + # Display decode vs prefill results console.print("\n[bold green]Decode vs Prefill Results:[/]") @@ -858,15 +1069,20 @@ def main(): base_config_args = { "num_layers": args.num_layers, "head_dim": args.head_dim, + "v_head_dim": args.v_head_dim, "num_q_heads": args.num_q_heads, "num_kv_heads": args.num_kv_heads, "block_size": args.block_size, "device": args.device, - "repeats": args.repeats, - "warmup_iters": args.warmup_iters, "profile_memory": args.profile_memory, "kv_cache_dtype": args.kv_cache_dtype, "use_cuda_graphs": args.cuda_graphs, + "ncu_profile": args.ncu_profile, + "warmup_ms": args.warmup_ms, + "num_splits": args.num_splits, + "kv_lora_rank": args.kv_lora_rank, + "qk_nope_head_dim": args.qk_nope_head_dim, + "qk_rope_head_dim": args.qk_rope_head_dim, } all_results = run_model_parameter_sweep( backends, @@ -882,15 +1098,17 @@ def main(): base_config_args = { "num_layers": args.num_layers, "head_dim": args.head_dim, + "v_head_dim": args.v_head_dim, "num_q_heads": args.num_q_heads, "num_kv_heads": args.num_kv_heads, "block_size": args.block_size, "device": args.device, - "repeats": args.repeats, - "warmup_iters": args.warmup_iters, "profile_memory": args.profile_memory, "kv_cache_dtype": args.kv_cache_dtype, "use_cuda_graphs": args.cuda_graphs, + "ncu_profile": args.ncu_profile, + "warmup_ms": args.warmup_ms, + "num_splits": args.num_splits, } all_results = run_parameter_sweep( backends, args.batch_specs, base_config_args, args.parameter_sweep, console @@ -914,15 +1132,17 @@ def main(): batch_spec=spec, num_layers=args.num_layers, head_dim=args.head_dim, + v_head_dim=getattr(args, "v_head_dim", None), num_q_heads=args.num_q_heads, num_kv_heads=args.num_kv_heads, block_size=args.block_size, device=args.device, - repeats=args.repeats, - warmup_iters=args.warmup_iters, profile_memory=args.profile_memory, kv_cache_dtype=args.kv_cache_dtype, use_cuda_graphs=args.cuda_graphs, + ncu_profile=args.ncu_profile, + warmup_ms=args.warmup_ms, + num_splits=args.num_splits, ) result = run_benchmark(config) @@ -935,9 +1155,10 @@ def main(): pbar.update(1) - console.print("\n[bold green]Results:[/]") - formatter = ResultsFormatter(console) - formatter.print_table(decode_results, backends) + if not args.ncu_profile: + console.print("\n[bold green]Results:[/]") + formatter = ResultsFormatter(console) + formatter.print_table(decode_results, backends) # Run prefill backend comparison if prefill_backends: @@ -962,9 +1183,8 @@ def main(): num_kv_heads=args.num_kv_heads, block_size=args.block_size, device=args.device, - repeats=args.repeats, - warmup_iters=args.warmup_iters, profile_memory=args.profile_memory, + warmup_ms=args.warmup_ms, prefill_backend=pb, ) @@ -980,16 +1200,17 @@ def main(): pbar.update(1) - console.print("\n[bold green]Prefill Backend Results:[/]") - formatter = ResultsFormatter(console) - formatter.print_table( - prefill_results, prefill_backends, compare_to_fastest=True - ) + if not args.ncu_profile: + console.print("\n[bold green]Prefill Backend Results:[/]") + formatter = ResultsFormatter(console) + formatter.print_table( + prefill_results, prefill_backends, compare_to_fastest=True + ) all_results = decode_results + prefill_results - # Save results - if all_results: + # Save results (skip ncu profiling runs: timings are placeholder zeros) + if all_results and not args.ncu_profile: formatter = ResultsFormatter(console) if args.output_csv: formatter.save_csv(all_results, args.output_csv) diff --git a/benchmarks/attention_benchmarks/common.py b/benchmarks/attention_benchmarks/common.py index 74d9e239725d..106d7854804f 100644 --- a/benchmarks/attention_benchmarks/common.py +++ b/benchmarks/attention_benchmarks/common.py @@ -15,6 +15,8 @@ from rich.console import Console from rich.table import Table +from vllm.triton_utils import triton + def batch_spec_sort_key(spec: str) -> tuple[int, int, int]: """ @@ -34,6 +36,30 @@ def batch_spec_sort_key(spec: str) -> tuple[int, int, int]: return (0, 0, 0) +def run_do_bench( + benchmark_fn, + use_cuda_graphs: bool, + warmup_ms: int | None = None, +) -> list[float]: + kwargs: dict[str, Any] = {"return_mode": "all"} + if use_cuda_graphs: + result = triton.testing.do_bench_cudagraph(benchmark_fn, **kwargs) + else: + if warmup_ms is not None: + kwargs["warmup"] = warmup_ms + result = triton.testing.do_bench(benchmark_fn, **kwargs) + return result + + +def run_ncu_profile(benchmark_fn) -> None: + benchmark_fn() + torch.accelerator.synchronize() + torch.cuda.cudart().cudaProfilerStart() + benchmark_fn() + torch.accelerator.synchronize() + torch.cuda.cudart().cudaProfilerStop() + + # Mock classes for vLLM attention infrastructure @@ -182,18 +208,37 @@ def get_label(self, backend: str, value: Any) -> str: @dataclass class ModelParameterSweep: - """Configuration for sweeping a model configuration parameter.""" + """Configuration for sweeping model configuration parameter(s). - param_name: str # Name of the model config parameter to sweep (e.g., "num_q_heads") - values: list[Any] # List of values to test - label_format: str = "{backend}_{param_name}_{value}" # Result label template + Supports two modes: + - Single param: param_name="head_dim", values=[128, 256, 512] + - Multi param: values=[{head_dim: 192, v_head_dim: 128}, {head_dim: 256}] + When values are dicts, each dict's keys are applied as config overrides. + """ + + param_name: str | None = None + values: list[Any] | None = None + label_format: str = "{backend}_{param_name}_{value}" def get_label(self, backend: str, value: Any) -> str: """Generate a label for a specific parameter value.""" + if isinstance(value, dict): + return self.label_format.format( + backend=backend, param_name=self.param_name, value=value, **value + ) return self.label_format.format( backend=backend, param_name=self.param_name, value=value ) + def apply(self, config_args: dict, value: Any) -> None: + """Apply a sweep value to config args.""" + if isinstance(value, dict): + config_args.update(value) + elif self.param_name is not None: + config_args[self.param_name] = value + else: + raise ValueError("param_name must be set if sweep values are not dicts") + @dataclass class BenchmarkConfig: @@ -208,10 +253,10 @@ class BenchmarkConfig: block_size: int device: str dtype: torch.dtype = torch.float16 - repeats: int = 1 - warmup_iters: int = 3 profile_memory: bool = False use_cuda_graphs: bool = False + ncu_profile: bool = False + warmup_ms: int | None = None # "auto" or "fp8" kv_cache_dtype: str = "auto" @@ -226,6 +271,7 @@ class BenchmarkConfig: # Backend-specific tuning num_kv_splits: int | None = None # CUTLASS MLA reorder_batch_threshold: int | None = None # FlashAttn MLA, FlashMLA + num_splits: int | None = None # FlashAttention split-K (0=auto, 1=disabled) @dataclass @@ -234,6 +280,7 @@ class BenchmarkResult: config: BenchmarkConfig mean_time: float # seconds + median_time: float # seconds std_time: float # seconds min_time: float # seconds max_time: float # seconds @@ -252,6 +299,7 @@ def to_dict(self) -> dict[str, Any]: return { "config": asdict(self.config), "mean_time": self.mean_time, + "median_time": self.median_time, "std_time": self.std_time, "min_time": self.min_time, "max_time": self.max_time, diff --git a/benchmarks/attention_benchmarks/configs/mla_decode.yaml b/benchmarks/attention_benchmarks/configs/mla_decode.yaml index 8f12ac723064..c1d47bf5748b 100644 --- a/benchmarks/attention_benchmarks/configs/mla_decode.yaml +++ b/benchmarks/attention_benchmarks/configs/mla_decode.yaml @@ -56,8 +56,6 @@ backends: - TOKENSPEED_MLA # Blackwell + R1 dims + FP8 KV (use --kv-cache-dtype fp8) device: "cuda:0" -repeats: 100 -warmup_iters: 10 profile_memory: true # Backend-specific tuning diff --git a/benchmarks/attention_benchmarks/configs/mla_fa4_fp8_output.yaml b/benchmarks/attention_benchmarks/configs/mla_fa4_fp8_output.yaml new file mode 100644 index 000000000000..85588fcf9584 --- /dev/null +++ b/benchmarks/attention_benchmarks/configs/mla_fa4_fp8_output.yaml @@ -0,0 +1,44 @@ +# MLA prefill FP8-output microbenchmark (FA4). +# Compares the fused FP8 write against bf16 attention + a standalone static-FP8 +# quant; the delta is the post-quant kernel the fused path removes. +# DeepSeek-Coder-V2-Lite dims; FA4 needs SM100/110. +# +# Usage: +# python benchmark.py --config configs/mla_fa4_fp8_output.yaml + +description: "MLA prefill FA4 fused-FP8 output vs post-quant" + +model: + name: "deepseek-v2-lite" + num_layers: 27 + num_q_heads: 16 + num_kv_heads: 1 + head_dim: 576 + kv_lora_rank: 512 + qk_nope_head_dim: 128 + qk_rope_head_dim: 64 + v_head_dim: 128 + block_size: 128 + +# Pure prefill (q_len == kv_len) so every token goes through forward_mha. +batch_specs: + - "q512" + - "q1k" + - "q2k" + - "q4k" + - "q8k" + - "2q4k" + - "4q4k" + - "8q4k" + +# Only used to construct the MLA impl; the pure-prefill specs skip decode. +decode_backends: + - CUTLASS_MLA + +# Sweep the two FP8 write paths (prefill backend is fixed to fa4). +fp8_output_scale: 0.1 +fuse_quant_op: [false, true] + +device: "cuda:0" +repeats: 50 +warmup_iters: 10 diff --git a/benchmarks/attention_benchmarks/configs/mla_mixed_batch.yaml b/benchmarks/attention_benchmarks/configs/mla_mixed_batch.yaml index c342e9fb8c1a..fcb1d8639b73 100644 --- a/benchmarks/attention_benchmarks/configs/mla_mixed_batch.yaml +++ b/benchmarks/attention_benchmarks/configs/mla_mixed_batch.yaml @@ -51,8 +51,6 @@ backends: - FLASHMLA # Hopper only device: "cuda:0" -repeats: 5 -warmup_iters: 3 profile_memory: true # Analyze chunked prefill workspace size impact diff --git a/benchmarks/attention_benchmarks/configs/mla_prefill.yaml b/benchmarks/attention_benchmarks/configs/mla_prefill.yaml index 1e1ab264bace..f39cdd8d1c2f 100644 --- a/benchmarks/attention_benchmarks/configs/mla_prefill.yaml +++ b/benchmarks/attention_benchmarks/configs/mla_prefill.yaml @@ -124,5 +124,3 @@ prefill_backends: - tokenspeed device: "cuda:0" -repeats: 20 -warmup_iters: 5 diff --git a/benchmarks/attention_benchmarks/configs/mla_sparse_decode.yaml b/benchmarks/attention_benchmarks/configs/mla_sparse_decode.yaml index 689c9f3c3c66..c791638241f7 100644 --- a/benchmarks/attention_benchmarks/configs/mla_sparse_decode.yaml +++ b/benchmarks/attention_benchmarks/configs/mla_sparse_decode.yaml @@ -53,6 +53,4 @@ backends: - FLASHINFER_MLA_SPARSE device: "cuda:0" -repeats: 100 -warmup_iters: 10 profile_memory: true diff --git a/benchmarks/attention_benchmarks/configs/mla_sparse_prefill.yaml b/benchmarks/attention_benchmarks/configs/mla_sparse_prefill.yaml index ef6b2cb07dc7..fd8a0e22c5e0 100644 --- a/benchmarks/attention_benchmarks/configs/mla_sparse_prefill.yaml +++ b/benchmarks/attention_benchmarks/configs/mla_sparse_prefill.yaml @@ -57,6 +57,4 @@ backends: - FLASHINFER_MLA_SPARSE device: "cuda:0" -repeats: 10 -warmup_iters: 3 profile_memory: true diff --git a/benchmarks/attention_benchmarks/configs/reorder_threshold.yaml b/benchmarks/attention_benchmarks/configs/reorder_threshold.yaml index 0d76ef0a358c..9f53eac2c9cb 100644 --- a/benchmarks/attention_benchmarks/configs/reorder_threshold.yaml +++ b/benchmarks/attention_benchmarks/configs/reorder_threshold.yaml @@ -63,8 +63,6 @@ model: # Benchmark settings device: "cuda:0" -repeats: 15 # More repeats for spec decode variance -warmup_iters: 5 profile_memory: false # Output diff --git a/benchmarks/attention_benchmarks/configs/speculative_decode.yaml b/benchmarks/attention_benchmarks/configs/speculative_decode.yaml index 47b6d3604d1d..5e8775f0a426 100644 --- a/benchmarks/attention_benchmarks/configs/speculative_decode.yaml +++ b/benchmarks/attention_benchmarks/configs/speculative_decode.yaml @@ -49,8 +49,6 @@ backends: # Benchmark settings device: "cuda:0" -repeats: 10 # More repeats for statistical significance -warmup_iters: 5 profile_memory: false # Test these threshold values for optimization diff --git a/benchmarks/attention_benchmarks/configs/standard_attention.yaml b/benchmarks/attention_benchmarks/configs/standard_attention.yaml index deb5a4b27ff3..ccd44a426b90 100644 --- a/benchmarks/attention_benchmarks/configs/standard_attention.yaml +++ b/benchmarks/attention_benchmarks/configs/standard_attention.yaml @@ -43,6 +43,4 @@ backends: - FLASHINFER device: "cuda:0" -repeats: 5 -warmup_iters: 3 profile_memory: false diff --git a/benchmarks/attention_benchmarks/configs/standard_decode.yaml b/benchmarks/attention_benchmarks/configs/standard_decode.yaml new file mode 100644 index 000000000000..0861bd63dad3 --- /dev/null +++ b/benchmarks/attention_benchmarks/configs/standard_decode.yaml @@ -0,0 +1,142 @@ +# Standard attention decode benchmark configuration +# Sweeps num_q_heads and num_kv_heads to isolate effects of: +# 1. GQA ratio (fixed num_q_heads=32, vary num_kv_heads) +# 2. Absolute head count (fixed 4:1 ratio, vary scale) + +model: + num_layers: 32 + num_q_heads: 32 # Base value, overridden by sweep + num_kv_heads: 8 # Base value, overridden by sweep + head_dim: 128 + block_size: 16 + +# Head count sweep: each entry overrides num_q_heads, num_kv_heads, and +# head_dim where it differs from the base (128). Head counts are per-GPU +# (i.e. after TP sharding). +# +# Group A — vary GQA ratio (fixed q=32, head_dim=128): +# 32:32 (MHA), 32:8 (GQA 4:1), 32:4 (GQA 8:1), 32:1 (MQA) +# +# Groups B-E — real model configs at various TP degrees: +# Model head_dim Full TP2 TP4 TP8 +# Llama 3 8B 128 32:8 16:4 8:2 4:1 +# Llama 3 70B 128 64:8 32:4 16:2 8:1 +# GPT-OSS 120B 64 64:8 32:4 16:2 8:1 +# Llama 3 405B 128 128:8 64:4 32:2 16:1 +model_parameter_sweep: + values: + # --- head_dim=128 (Llama 3 family) --- + - { num_q_heads: 32, num_kv_heads: 32, head_dim: 128 } # MHA 1:1 + - { num_q_heads: 32, num_kv_heads: 1, head_dim: 128 } # MQA 32:1 + - { num_q_heads: 4, num_kv_heads: 1, head_dim: 128 } # Llama 3 8B TP8 + - { num_q_heads: 8, num_kv_heads: 2, head_dim: 128 } # Llama 3 8B TP4 + - { num_q_heads: 16, num_kv_heads: 4, head_dim: 128 } # Llama 3 8B TP2 + - { num_q_heads: 32, num_kv_heads: 8, head_dim: 128 } # Llama 3 8B TP1 / GQA 4:1 + - { num_q_heads: 8, num_kv_heads: 1, head_dim: 128 } # Llama 3 70B TP8 + - { num_q_heads: 16, num_kv_heads: 2, head_dim: 128 } # Llama 3 70B TP4 + - { num_q_heads: 32, num_kv_heads: 4, head_dim: 128 } # Llama 3 70B TP2 / GQA 8:1 + - { num_q_heads: 64, num_kv_heads: 8, head_dim: 128 } # Llama 3 70B TP1 + - { num_q_heads: 16, num_kv_heads: 1, head_dim: 128 } # Llama 3 405B TP8 + - { num_q_heads: 32, num_kv_heads: 2, head_dim: 128 } # Llama 3 405B TP4 + - { num_q_heads: 64, num_kv_heads: 4, head_dim: 128 } # Llama 3 405B TP2 + - { num_q_heads: 128, num_kv_heads: 8, head_dim: 128 } # Llama 3 405B TP1 + # --- head_dim=64 (GPT-OSS 120B) --- + - { num_q_heads: 8, num_kv_heads: 1, head_dim: 64 } # GPT-OSS 120B TP8 + - { num_q_heads: 16, num_kv_heads: 2, head_dim: 64 } # GPT-OSS 120B TP4 + - { num_q_heads: 32, num_kv_heads: 4, head_dim: 64 } # GPT-OSS 120B TP2 + - { num_q_heads: 64, num_kv_heads: 8, head_dim: 64 } # GPT-OSS 120B TP1 + label_format: "{backend}_q{num_q_heads}kv{num_kv_heads}d{head_dim}" + +batch_specs: + # ---- batch_size x seq_len grid (decode: q_len=1) ---- + # Small grid for quick iteration. Uncomment for full sweep. + + # Batch size 1 + - "q1s1k" + - "q1s512" + - "q1s2k" + - "q1s4k" + - "q1s8k" + - "q1s16k" + - "q1s32k" + + # Batch size 2 + - "2q1s512" + - "2q1s1k" + - "2q1s2k" + - "2q1s4k" + - "2q1s8k" + - "2q1s16k" + - "2q1s32k" + + # Batch size 4 + - "4q1s512" + - "4q1s1k" + - "4q1s2k" + - "4q1s4k" + - "4q1s8k" + - "4q1s16k" + - "4q1s32k" + + # Batch size 8 + - "8q1s1k" + - "8q1s512" + - "8q1s2k" + - "8q1s4k" + - "8q1s8k" + - "8q1s16k" + - "8q1s32k" + + # Batch size 16 + - "16q1s512" + - "16q1s1k" + - "16q1s2k" + - "16q1s4k" + - "16q1s8k" + - "16q1s16k" + - "16q1s32k" + + # Batch size 32 + - "32q1s512" + - "32q1s1k" + - "32q1s2k" + - "32q1s4k" + - "32q1s8k" + - "32q1s16k" + - "32q1s32k" + + # Batch size 64 + - "64q1s1k" + - "64q1s512" + - "64q1s2k" + - "64q1s4k" + - "64q1s8k" + - "64q1s16k" + - "64q1s32k" + + # Batch size 128 + - "128q1s512" + - "128q1s1k" + - "128q1s2k" + - "128q1s4k" + - "128q1s8k" + - "128q1s16k" + - "128q1s32k" + + # Batch size 256 + - "256q1s1k" + - "256q1s512" + - "256q1s2k" + - "256q1s4k" + - "256q1s8k" + - "256q1s16k" + - "256q1s32k" + +# Available backends: FLASH_ATTN, TRITON_ATTN, FLASHINFER +backends: + - FLASH_ATTN + - TRITON_ATTN + - FLASHINFER + +device: "cuda:0" +profile_memory: false diff --git a/benchmarks/attention_benchmarks/configs/standard_prefill.yaml b/benchmarks/attention_benchmarks/configs/standard_prefill.yaml new file mode 100644 index 000000000000..278b6347f652 --- /dev/null +++ b/benchmarks/attention_benchmarks/configs/standard_prefill.yaml @@ -0,0 +1,108 @@ +# Standard attention prefill benchmark configuration +# Sweeps num_q_heads and num_kv_heads to isolate effects of: +# 1. GQA ratio (fixed num_q_heads=32, vary num_kv_heads) +# 2. Absolute head count (fixed 4:1 ratio, vary scale) + +model: + num_layers: 32 + num_q_heads: 32 # Base value, overridden by sweep + num_kv_heads: 8 # Base value, overridden by sweep + head_dim: 128 + block_size: 16 + +# Head count sweep: each entry overrides num_q_heads, num_kv_heads, and +# head_dim where it differs from the base (128). Head counts are per-GPU +# (i.e. after TP sharding). +# +# Group A — vary GQA ratio (fixed q=32, head_dim=128): +# 32:32 (MHA), 32:8 (GQA 4:1), 32:4 (GQA 8:1), 32:1 (MQA) +# +# Groups B-E — real model configs at various TP degrees: +# Model head_dim Full TP2 TP4 TP8 +# Llama 3 8B 128 32:8 16:4 8:2 4:1 +# Llama 3 70B 128 64:8 32:4 16:2 8:1 +# GPT-OSS 120B 64 64:8 32:4 16:2 8:1 +# Llama 3 405B 128 128:8 64:4 32:2 16:1 +model_parameter_sweep: + values: + # --- head_dim=128 (Llama 3 family) --- + - { num_q_heads: 32, num_kv_heads: 32, head_dim: 128 } # MHA 1:1 + - { num_q_heads: 32, num_kv_heads: 1, head_dim: 128 } # MQA 32:1 + - { num_q_heads: 4, num_kv_heads: 1, head_dim: 128 } # Llama 3 8B TP8 + - { num_q_heads: 8, num_kv_heads: 2, head_dim: 128 } # Llama 3 8B TP4 + - { num_q_heads: 16, num_kv_heads: 4, head_dim: 128 } # Llama 3 8B TP2 + - { num_q_heads: 32, num_kv_heads: 8, head_dim: 128 } # Llama 3 8B TP1 / GQA 4:1 + - { num_q_heads: 8, num_kv_heads: 1, head_dim: 128 } # Llama 3 70B TP8 + - { num_q_heads: 16, num_kv_heads: 2, head_dim: 128 } # Llama 3 70B TP4 + - { num_q_heads: 32, num_kv_heads: 4, head_dim: 128 } # Llama 3 70B TP2 / GQA 8:1 + - { num_q_heads: 64, num_kv_heads: 8, head_dim: 128 } # Llama 3 70B TP1 + - { num_q_heads: 16, num_kv_heads: 1, head_dim: 128 } # Llama 3 405B TP8 + - { num_q_heads: 32, num_kv_heads: 2, head_dim: 128 } # Llama 3 405B TP4 + - { num_q_heads: 64, num_kv_heads: 4, head_dim: 128 } # Llama 3 405B TP2 + - { num_q_heads: 128, num_kv_heads: 8, head_dim: 128 } # Llama 3 405B TP1 + # --- head_dim=64 (GPT-OSS 120B) --- + - { num_q_heads: 8, num_kv_heads: 1, head_dim: 64 } # GPT-OSS 120B TP8 + - { num_q_heads: 16, num_kv_heads: 2, head_dim: 64 } # GPT-OSS 120B TP4 + - { num_q_heads: 32, num_kv_heads: 4, head_dim: 64 } # GPT-OSS 120B TP2 + - { num_q_heads: 64, num_kv_heads: 8, head_dim: 64 } # GPT-OSS 120B TP1 + label_format: "{backend}_q{num_q_heads}kv{num_kv_heads}d{head_dim}" + +batch_specs: + # ---- batch_size x prefill_len grid (prefill: q_len == seq_len) ---- + # Total tokens = batch_size * prefill_len, and prefill compute scales with + # prefill_len^2, so the largest cells are expensive. Trim batch sizes or + # lengths for quick iteration. + + # Batch size 1 + - "q512" + - "q1k" + - "q2k" + - "q4k" + - "q8k" + - "q16k" + - "q32k" + + # Batch size 2 + - "2q512" + - "2q1k" + - "2q2k" + - "2q4k" + - "2q8k" + - "2q16k" + - "2q32k" + + # Batch size 4 + - "4q512" + - "4q1k" + - "4q2k" + - "4q4k" + - "4q8k" + - "4q16k" + - "4q32k" + + # Batch size 8 + - "8q512" + - "8q1k" + - "8q2k" + - "8q4k" + - "8q8k" + - "8q16k" + - "8q32k" + + # Batch size 16 + - "16q512" + - "16q1k" + - "16q2k" + - "16q4k" + - "16q8k" + - "16q16k" + - "16q32k" + +# Available backends: FLASH_ATTN, TRITON_ATTN, FLASHINFER +backends: + - FLASH_ATTN + - TRITON_ATTN + - FLASHINFER + +device: "cuda:0" +profile_memory: false diff --git a/benchmarks/attention_benchmarks/mla_runner.py b/benchmarks/attention_benchmarks/mla_runner.py index abab1e2edbac..c9b3fb29bb92 100644 --- a/benchmarks/attention_benchmarks/mla_runner.py +++ b/benchmarks/attention_benchmarks/mla_runner.py @@ -8,6 +8,8 @@ needing full VllmConfig integration. """ +import statistics + import numpy as np import torch from batch_spec import parse_batch_spec @@ -17,6 +19,8 @@ MockIndexer, MockKVBProj, MockLayer, + run_do_bench, + run_ncu_profile, setup_mla_dims, ) @@ -704,6 +708,8 @@ def _run_single_benchmark( device: torch.device, indexer=None, kv_cache_dtype: str | None = None, + output_scale: float | None = None, + fuse_quant_op: bool = False, ) -> BenchmarkResult: """ Run a single benchmark iteration. @@ -717,6 +723,11 @@ def _run_single_benchmark( mla_dims: MLA dimension configuration device: Target device indexer: Optional MockIndexer for sparse backends + output_scale: Static per-tensor FP8 scale for prefill output. None + keeps the plain bf16 output (no quantization). + fuse_quant_op: With output_scale set, True lets the prefill kernel write + FP8 directly; False runs bf16 attention then a standalone static-FP8 + quant. The delta isolates the saved post-quant kernel. Returns: BenchmarkResult with timing statistics @@ -820,63 +831,86 @@ def _run_single_benchmark( num_prefill, mla_dims, query_fmt, device, torch.bfloat16 ) - # Build forward function + # Prefill FP8 output: fused (kernel writes e4m3) vs separate post-quant. + prefill_fp8_output = None + prefill_output_scale = None + prefill_quant_op = None + if has_prefill and output_scale is not None: + from vllm.platforms import current_platform + + prefill_output_scale = torch.tensor( + [output_scale], device=device, dtype=torch.float32 + ) + if fuse_quant_op: + prefill_fp8_output = torch.empty_like( + prefill_inputs["output"], dtype=current_platform.fp8_dtype() + ) + else: + from vllm.model_executor.layers.quantization.input_quant_fp8 import ( + QuantFP8, + ) + from vllm.model_executor.layers.quantization.utils.quant_utils import ( + GroupShape, + ) + + prefill_quant_op = QuantFP8(static=True, group_shape=GroupShape.PER_TENSOR) + + fused_output = output_scale is not None and fuse_quant_op + + # Build forward function (runs a single decode/prefill pass) def forward_fn(): results = [] if has_decode: results.append(impl.forward_mqa(decode_inputs, kv_cache, metadata, layer)) if has_prefill: - results.append( - impl.forward_mha( - prefill_inputs["q"], - prefill_inputs["k_c_normed"], - prefill_inputs["k_pe"], - kv_cache, - metadata, - prefill_inputs["k_scale"], - prefill_inputs["output"], - ) + out = impl.forward_mha( + prefill_inputs["q"], + prefill_inputs["k_c_normed"], + prefill_inputs["k_pe"], + kv_cache, + metadata, + prefill_inputs["k_scale"], + prefill_fp8_output if fused_output else prefill_inputs["output"], + prefill_output_scale if fused_output else None, ) + if fused_output: + out = prefill_fp8_output + elif prefill_quant_op is not None: + out, _ = prefill_quant_op( + prefill_inputs["output"], prefill_output_scale + ) + results.append(out) return results[0] if len(results) == 1 else tuple(results) - # Warmup - for _ in range(config.warmup_iters): - forward_fn() - torch.accelerator.synchronize() - - # Optionally capture a CUDA graph after warmup. - # Graph replay eliminates CPU launch overhead so timings reflect pure - # kernel time. - if config.use_cuda_graphs: - graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(graph): + def benchmark_fn(): + for _ in range(config.num_layers): forward_fn() - benchmark_fn = graph.replay - else: - benchmark_fn = forward_fn - # Benchmark - times = [] - for _ in range(config.repeats): - start = torch.cuda.Event(enable_timing=True) - end = torch.cuda.Event(enable_timing=True) + if config.ncu_profile: + run_ncu_profile(benchmark_fn) + return BenchmarkResult( + config=config, + mean_time=0.0, + median_time=0.0, + std_time=0.0, + min_time=0.0, + max_time=0.0, + throughput_tokens_per_sec=0.0, + ) - start.record() - for _ in range(config.num_layers): - benchmark_fn() - end.record() + all_ms = run_do_bench(benchmark_fn, config.use_cuda_graphs, config.warmup_ms) - torch.accelerator.synchronize() - elapsed_ms = start.elapsed_time(end) - times.append(elapsed_ms / 1000.0 / config.num_layers) + # Convert ms to seconds per layer + times = [t / 1000.0 / config.num_layers for t in all_ms] + mean_time = statistics.mean(times) - mean_time = float(np.mean(times)) return BenchmarkResult( config=config, mean_time=mean_time, - std_time=float(np.std(times)), - min_time=float(np.min(times)), - max_time=float(np.max(times)), + median_time=statistics.median(times), + std_time=statistics.stdev(times) if len(times) > 1 else 0.0, + min_time=min(times), + max_time=max(times), throughput_tokens_per_sec=total_q / mean_time if mean_time > 0 else 0, ) @@ -886,6 +920,8 @@ def _run_mla_benchmark_batched( configs_with_params: list[tuple], # [(config, threshold, num_splits), ...] index_topk: int = 2048, prefill_backend: str | None = None, + output_scale: float | None = None, + fuse_quant_op: bool = False, ) -> list[BenchmarkResult]: """ Unified batched MLA benchmark runner for all backends. @@ -1025,6 +1061,8 @@ def _run_mla_benchmark_batched( device, indexer=indexer, kv_cache_dtype=kv_cache_dtype, + output_scale=output_scale, + fuse_quant_op=fuse_quant_op, ) results.append(result) @@ -1052,6 +1090,8 @@ def run_mla_benchmark( num_kv_splits: int | None = None, index_topk: int = 2048, prefill_backend: str | None = None, + output_scale: float | None = None, + fuse_quant_op: bool = False, ) -> BenchmarkResult | list[BenchmarkResult]: """ Unified MLA benchmark runner for all backends. @@ -1071,6 +1111,9 @@ def run_mla_benchmark( index_topk: Topk value for sparse MLA backends (default 2048) prefill_backend: Prefill backend name (e.g., "fa3", "fa4"). When set, forces the specified FlashAttention version for prefill. + output_scale: Static per-tensor FP8 scale for prefill output (None = bf16). + fuse_quant_op: With output_scale set, fuse the FP8 write into the prefill + kernel vs a standalone post-quant kernel. See _run_single_benchmark. Returns: BenchmarkResult (single mode) or list of BenchmarkResult (batched mode) @@ -1095,7 +1138,12 @@ def run_mla_benchmark( # Use unified batched execution results = _run_mla_benchmark_batched( - backend, configs_with_params, index_topk, prefill_backend=prefill_backend + backend, + configs_with_params, + index_topk, + prefill_backend=prefill_backend, + output_scale=output_scale, + fuse_quant_op=fuse_quant_op, ) # Return single result or list based on input diff --git a/benchmarks/attention_benchmarks/runner.py b/benchmarks/attention_benchmarks/runner.py index aa636cd9cb53..8cd20dced179 100644 --- a/benchmarks/attention_benchmarks/runner.py +++ b/benchmarks/attention_benchmarks/runner.py @@ -9,13 +9,20 @@ """ import logging +import statistics import types from contextlib import contextmanager -import numpy as np import torch from batch_spec import parse_batch_spec, reorder_for_flashinfer -from common import BenchmarkConfig, BenchmarkResult, MockLayer, get_attention_scale +from common import ( + BenchmarkConfig, + BenchmarkResult, + MockLayer, + get_attention_scale, + run_do_bench, + run_ncu_profile, +) from vllm.config import ( CacheConfig, @@ -208,6 +215,13 @@ def _create_backend_impl( scale = get_attention_scale(config.head_dim) + # Set v_head_dim for diff-headdim backends. Always reset (defaulting to + # head_dim) so a prior run's value doesn't leak into this one via the + # backend's class-level state. + if hasattr(backend_class, "set_head_size_v"): + v_dim = config.v_head_dim if config.v_head_dim is not None else config.head_dim + backend_class.set_head_size_v(v_dim) + impl = backend_class.get_impl_cls()( num_heads=config.num_q_heads, head_size=config.head_dim, @@ -300,6 +314,7 @@ def _create_input_tensors( from vllm.platforms import current_platform q_dtype = current_platform.fp8_dtype() + v_dim = config.v_head_dim if config.v_head_dim is not None else config.head_dim q_list = [ torch.randn( total_q, config.num_q_heads, config.head_dim, device=device, dtype=dtype @@ -313,9 +328,7 @@ def _create_input_tensors( for _ in range(config.num_layers) ] v_list = [ - torch.randn( - total_q, config.num_kv_heads, config.head_dim, device=device, dtype=dtype - ) + torch.randn(total_q, config.num_kv_heads, v_dim, device=device, dtype=dtype) for _ in range(config.num_layers) ] return q_list, k_list, v_list @@ -389,14 +402,17 @@ def _run_single_benchmark( device: torch.device, dtype: torch.dtype, ) -> tuple: - """Run single benchmark iteration with warmup and timing loop.""" + """Run single benchmark using triton's do_bench_cudagraph/do_bench. + + Returns: + (timing_stats, mem_stats) where timing_stats is a dict with + mean/std/min/max in seconds per layer. + """ total_q = q_list[0].shape[0] - out = torch.empty( - total_q, config.num_q_heads, config.head_dim, device=device, dtype=dtype - ) + v_dim = config.v_head_dim if config.v_head_dim is not None else config.head_dim + out = torch.empty(total_q, config.num_q_heads, v_dim, device=device, dtype=dtype) - # Warmup - for _ in range(config.warmup_iters): + def benchmark_fn(): for i in range(config.num_layers): impl.forward( layer, @@ -407,52 +423,22 @@ def _run_single_benchmark( attn_metadata, output=out, ) - torch.accelerator.synchronize() - - # Optionally capture a CUDA graph after warmup. - # Graph replay eliminates CPU launch overhead so timings reflect pure - # kernel time. - if config.use_cuda_graphs: - graph = torch.cuda.CUDAGraph() - with torch.cuda.graph(graph): - for i in range(config.num_layers): - impl.forward( - layer, - q_list[i], - k_list[i], - v_list[i], - cache_list[i], - attn_metadata, - output=out, - ) - benchmark_fn = graph.replay - else: - - def benchmark_fn(): - for i in range(config.num_layers): - impl.forward( - layer, - q_list[i], - k_list[i], - v_list[i], - cache_list[i], - attn_metadata, - output=out, - ) - - # Benchmark - times = [] - for _ in range(config.repeats): - start = torch.cuda.Event(enable_timing=True) - end = torch.cuda.Event(enable_timing=True) - start.record() - benchmark_fn() - end.record() - - torch.accelerator.synchronize() - elapsed_ms = start.elapsed_time(end) - times.append(elapsed_ms / 1000.0 / config.num_layers) # seconds per layer + if config.ncu_profile: + run_ncu_profile(benchmark_fn) + timing_stats = dict.fromkeys(("mean", "median", "std", "min", "max"), 0.0) + else: + all_ms = run_do_bench(benchmark_fn, config.use_cuda_graphs, config.warmup_ms) + + # Convert ms to seconds per layer + times = [t / 1000.0 / config.num_layers for t in all_ms] + timing_stats = { + "mean": statistics.mean(times), + "std": statistics.stdev(times) if len(times) > 1 else 0.0, + "min": min(times), + "max": max(times), + "median": statistics.median(times), + } mem_stats = {} if config.profile_memory: @@ -461,7 +447,7 @@ def benchmark_fn(): "reserved_mb": torch.accelerator.memory_reserved(device) / 1024**2, } - return times, mem_stats + return timing_stats, mem_stats # ============================================================================ @@ -541,6 +527,12 @@ def run_attention_benchmark(config: BenchmarkConfig) -> BenchmarkResult: common_attn_metadata=common_metadata, ) + # Override num_splits for split-K testing (FlashAttention only) + if config.num_splits is not None and hasattr( + attn_metadata, "max_num_splits" + ): + attn_metadata.max_num_splits = config.num_splits + # Only quantize queries when the impl supports it quantize_query = config.kv_cache_dtype.startswith("fp8") and getattr( impl, "supports_quant_query_input", False @@ -553,7 +545,7 @@ def run_attention_benchmark(config: BenchmarkConfig) -> BenchmarkResult: config, max_num_blocks, backend_class, device, dtype ) - times, mem_stats = _run_single_benchmark( + timing_stats, mem_stats = _run_single_benchmark( config, impl, layer, @@ -566,15 +558,16 @@ def run_attention_benchmark(config: BenchmarkConfig) -> BenchmarkResult: dtype, ) - mean_time = np.mean(times) + mean_time = timing_stats["mean"] throughput = total_q / mean_time if mean_time > 0 else 0 return BenchmarkResult( config=config, mean_time=mean_time, - std_time=np.std(times), - min_time=np.min(times), - max_time=np.max(times), + median_time=timing_stats["median"], + std_time=timing_stats["std"], + min_time=timing_stats["min"], + max_time=timing_stats["max"], throughput_tokens_per_sec=throughput, memory_allocated_mb=mem_stats.get("allocated_mb"), memory_reserved_mb=mem_stats.get("reserved_mb"), diff --git a/benchmarks/benchmark_pin_memory.py b/benchmarks/benchmark_pin_memory.py new file mode 100644 index 000000000000..63a6b75d914e --- /dev/null +++ b/benchmarks/benchmark_pin_memory.py @@ -0,0 +1,358 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Benchmark and regression-test pinned (page-locked) CPU memory for vLLM. + +Verifies that enabling pinned memory does not regress throughput or latency +compared to unpinned memory. Each condition runs in an isolated ``spawn`` +subprocess so both start from a cold CUDA context, giving an unbiased +comparison. + +Usage +----- +Run all tests with the default model:: + + python benchmarks/benchmark_pin_memory.py -v + +Override the model and optional max-model-len:: + + python benchmarks/benchmark_pin_memory.py --model unsloth/Qwen3-1.7B -v + python benchmarks/benchmark_pin_memory.py --model unsloth/Qwen3-1.7B \ + --max-model-len 8192 -v + +Run only throughput or latency tests:: + + python benchmarks/benchmark_pin_memory.py -v -k test_throughput + python benchmarks/benchmark_pin_memory.py -v -k test_latency + +Run only the v1 or v2 runner variant:: + + python benchmarks/benchmark_pin_memory.py -v -k v1 + python benchmarks/benchmark_pin_memory.py -v -k v2 + +Note: on WSL2, v1 runner tests are skipped because pin memory is not available +for the v1 runner without cpu_offload_gb. Run on other platforms to exercise v1. +""" + +import argparse +import json +import multiprocessing +import sys +import tempfile + +import pytest + +# Allow up to 2% degradation. Both benchmark runs start from an identical +# cold CUDA context (separate spawn subprocesses), so the measured difference +# reflects the genuine pin_memory overhead rather than cold/warm ordering bias. +_THROUGHPUT_TOLERANCE = 0.98 +_THROUGHPUT_NUM_REQUESTS = 200 +_THROUGHPUT_INPUT_LEN = 128 +_THROUGHPUT_OUTPUT_LEN = 512 +_THROUGHPUT_MAX_NUM_SEQS = 128 + +# Latency benchmark constants — match latency.py defaults. +_LATENCY_TOLERANCE = 1.02 # Allow up to 2% latency regression. +_LATENCY_BATCH_SIZE = 64 +_LATENCY_INPUT_LEN = 32 +_LATENCY_OUTPUT_LEN = 128 +_LATENCY_WARMUP_ITERS = 5 +_LATENCY_BENCH_ITERS = 15 + +_DEFAULT_MODEL = "unsloth/Qwen3-1.7B" +_DEFAULT_MAX_MODEL_LEN = 16384 + + +def _benchmark_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument("--model", default=_DEFAULT_MODEL) + parser.add_argument("--max-model-len", type=int, default=_DEFAULT_MAX_MODEL_LEN) + args, _ = parser.parse_known_args() + return args + + +@pytest.fixture +def model() -> str: + return _benchmark_args().model + + +@pytest.fixture +def max_model_len() -> int: + return _benchmark_args().max_model_len + + +def _skip_if_pin_memory_not_available(engine_args_kwargs: dict) -> None: + """Skip the current pytest test if pin_memory is unavailable for this config.""" + import vllm.utils.platform_utils as pu + from vllm.config import set_current_vllm_config + from vllm.engine.arg_utils import EngineArgs + + vllm_config = EngineArgs(**engine_args_kwargs).create_engine_config() + with set_current_vllm_config(vllm_config): + pu.is_pin_memory_available.cache_clear() + if not pu.is_pin_memory_available(): + import os + + runner = "v2" if os.environ.get("VLLM_USE_V2_MODEL_RUNNER") == "1" else "v1" + model = engine_args_kwargs.get("model", "unknown") + print( + f"\033[33mSKIP: pin_memory not available for " + f"{runner} runner, model={model}\033[0m" + ) + pytest.skip("pin_memory not available for this configuration") + + +def _throughput_worker( + pin: bool, + engine_args_kwargs: dict, + q: "multiprocessing.Queue[float]", + v2_mode: bool = False, +) -> None: + """Run throughput benchmark in a fresh spawn subprocess. + + Delegates to vllm/benchmarks/throughput.py main() using the random dataset, + so the methodology matches the official benchmark. Results are written to a + temp JSON file and forwarded through the queue as tokens/s. + + v2_mode: when True, monkeypatches is_uva_available() to always return True + so the v2 model runner's UVA buffers remain functional even when pin=False. + This isolates the non-UVA pin_memory paths in v2. + """ + import vllm.utils.platform_utils as pu + from vllm.platforms import current_platform + + pu.is_pin_memory_available.cache_clear() + pu.is_uva_available.cache_clear() + type(current_platform).is_pin_memory_available = classmethod(lambda cls: pin) + if v2_mode: + pu.is_uva_available = lambda: True + + from vllm.benchmarks.throughput import add_cli_args + from vllm.benchmarks.throughput import main as throughput_main + + parser = argparse.ArgumentParser() + add_cli_args(parser) + args = parser.parse_args([]) + + for key, val in engine_args_kwargs.items(): + setattr(args, key, val) + args.max_num_seqs = _THROUGHPUT_MAX_NUM_SEQS + args.dataset_name = "random" + args.input_len = _THROUGHPUT_INPUT_LEN + args.output_len = _THROUGHPUT_OUTPUT_LEN + # Nullify defaults that conflict with explicit input/output_len. + args.random_input_len = None + args.random_output_len = None + args.random_prefix_len = None + args.num_prompts = _THROUGHPUT_NUM_REQUESTS + args.seed = 0 + args.disable_detokenize = True + + with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f: + tmp_path = f.name + args.output_json = tmp_path + + throughput_main(args) + + with open(tmp_path) as f: + results = json.load(f) + q.put(results["tokens_per_second"]) + + +def _run_throughput_benchmark( + pin: bool, + engine_args_kwargs: dict, + v2_mode: bool = False, +) -> float: + ctx = multiprocessing.get_context("spawn") + q = ctx.Queue() + p = ctx.Process( + target=_throughput_worker, + args=(pin, engine_args_kwargs, q, v2_mode), + ) + p.start() + p.join() + if p.exitcode != 0: + raise RuntimeError( + f"Throughput benchmark subprocess (pin={pin}) exited with code {p.exitcode}" + ) + return q.get() + + +def _latency_worker( + pin: bool, + engine_args_kwargs: dict, + q: "multiprocessing.Queue[dict]", + v2_mode: bool = False, +) -> None: + """Run latency benchmark in a fresh spawn subprocess. + + Follows latency.py methodology: fixed batch of dummy token IDs, warmup + iterations to reach steady state, then timed iterations reduced to avg + and percentiles. Results are written to a temp JSON file by latency_main + and forwarded through the queue. + """ + import vllm.utils.platform_utils as pu + from vllm.platforms import current_platform + + pu.is_pin_memory_available.cache_clear() + pu.is_uva_available.cache_clear() + type(current_platform).is_pin_memory_available = classmethod(lambda cls: pin) + if v2_mode: + pu.is_uva_available = lambda: True + + from vllm.benchmarks.latency import add_cli_args + from vllm.benchmarks.latency import main as latency_main + + parser = argparse.ArgumentParser() + add_cli_args(parser) + args = parser.parse_args([]) + + for key, val in engine_args_kwargs.items(): + setattr(args, key, val) + args.input_len = _LATENCY_INPUT_LEN + args.output_len = _LATENCY_OUTPUT_LEN + args.batch_size = _LATENCY_BATCH_SIZE + args.num_iters_warmup = _LATENCY_WARMUP_ITERS + args.num_iters = _LATENCY_BENCH_ITERS + args.profile = False + args.disable_detokenize = True + + with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f: + tmp_path = f.name + args.output_json = tmp_path + + latency_main(args) + + with open(tmp_path) as f: + results = json.load(f) + q.put(results) + + +def _run_latency_benchmark( + pin: bool, + engine_args_kwargs: dict, + v2_mode: bool = False, +) -> dict: + ctx = multiprocessing.get_context("spawn") + q = ctx.Queue() + p = ctx.Process( + target=_latency_worker, + args=(pin, engine_args_kwargs, q, v2_mode), + ) + p.start() + p.join() + if p.exitcode != 0: + raise RuntimeError( + f"Latency benchmark subprocess (pin={pin}) exited with code {p.exitcode}" + ) + return q.get() + + +@pytest.mark.parametrize( + "test_v2_runner", + [ + pytest.param(False, id="v1"), + pytest.param(True, id="v2"), + ], +) +class TestPinnedMemory: + """Verify pinned memory yields >= throughput vs unpinned via real vLLM inference.""" + + def test_throughput(self, monkeypatch, test_v2_runner, model, max_model_len): + """Benchmark throughput with pin_memory forced on then off. + + Delegates to vllm/benchmarks/throughput.py main() with the random + dataset. Each condition runs in an isolated spawn subprocess so both + start from a cold CUDA context, giving an unbiased comparison. + """ + monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0") + monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1" if test_v2_runner else "0") + + engine_args_kwargs = dict( + model=model, + gpu_memory_utilization=0.88, + max_model_len=max_model_len, + enable_prefix_caching=False, + ) + + _skip_if_pin_memory_not_available(engine_args_kwargs) + + unpinned_tps = _run_throughput_benchmark( + False, engine_args_kwargs, v2_mode=test_v2_runner + ) + pinned_tps = _run_throughput_benchmark( + True, engine_args_kwargs, v2_mode=test_v2_runner + ) + + pct_diff = (pinned_tps - unpinned_tps) / unpinned_tps * 100 + runner = "v2" if test_v2_runner else "v1" + print( + f"\n=== Throughput results ({runner} runner, {model}) ===" + f"\npin_memory=True: {pinned_tps:.1f} tok/s" + f"\npin_memory=False: {unpinned_tps:.1f} tok/s" + f"\nDifference: {pct_diff:+.1f}% (pinned vs unpinned)" + ) + + assert pinned_tps >= unpinned_tps * _THROUGHPUT_TOLERANCE, ( + f"Pinned throughput ({pinned_tps:.1f} tok/s) fell more than " + f"{(1.0 - _THROUGHPUT_TOLERANCE) * 100:.1f}% below " + f"unpinned ({unpinned_tps:.1f} tok/s)." + ) + + def test_latency(self, monkeypatch, test_v2_runner, model, max_model_len): + """Benchmark per-batch latency with pin_memory forced on then off. + + Follows vllm/benchmarks/latency.py: fixed dummy-token batch, warmup + iterations to reach steady state, then timed iterations reduced to avg + and percentiles. Subprocesses run serially so each gets a cold CUDA + context without GPU memory pressure from the other run. + """ + monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0") + monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1" if test_v2_runner else "0") + + engine_args_kwargs = dict( + model=model, + gpu_memory_utilization=0.88, + max_model_len=max_model_len, + enable_prefix_caching=False, + ) + + _skip_if_pin_memory_not_available(engine_args_kwargs) + + unpinned = _run_latency_benchmark( + False, engine_args_kwargs, v2_mode=test_v2_runner + ) + pinned = _run_latency_benchmark( + True, engine_args_kwargs, v2_mode=test_v2_runner + ) + + pct_diff = ( + (pinned["avg_latency"] - unpinned["avg_latency"]) + / unpinned["avg_latency"] + * 100 + ) + runner = "v2" if test_v2_runner else "v1" + print( + f"\n=== Latency results ({runner} runner, {model}) ===" + f"\npin_memory=True: avg={pinned['avg_latency']:.3f}s" + f" p50={pinned['percentiles']['50']:.3f}s" + f" p99={pinned['percentiles']['99']:.3f}s" + f"\npin_memory=False: avg={unpinned['avg_latency']:.3f}s" + f" p50={unpinned['percentiles']['50']:.3f}s" + f" p99={unpinned['percentiles']['99']:.3f}s" + f"\nDifference: {pct_diff:+.1f}% (pinned vs unpinned)" + ) + + assert pinned["avg_latency"] <= unpinned["avg_latency"] * _LATENCY_TOLERANCE, ( + f"Pinned avg latency ({pinned['avg_latency']:.3f}s) exceeded " + f"unpinned ({unpinned['avg_latency']:.3f}s) by more than " + f"{(_LATENCY_TOLERANCE - 1.0) * 100:.1f}%." + ) + + +if __name__ == "__main__": + _parser = argparse.ArgumentParser(add_help=False) + _parser.add_argument("--model", default=_DEFAULT_MODEL) + _parser.add_argument("--max-model-len", type=int, default=_DEFAULT_MAX_MODEL_LEN) + _, _remaining = _parser.parse_known_args() + sys.exit(pytest.main([__file__] + _remaining)) diff --git a/benchmarks/kernels/benchmark_flydsl_moe_w4a16.py b/benchmarks/kernels/benchmark_flydsl_moe_w4a16.py new file mode 100644 index 000000000000..9e4f4157a8a4 --- /dev/null +++ b/benchmarks/kernels/benchmark_flydsl_moe_w4a16.py @@ -0,0 +1,277 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +# Copyright (c) 2025 FlyDSL Project Contributors + +import json +import os + +import torch +from aiter.test_common import run_perftest + +from vllm.model_executor.layers.fused_moe import fused_experts +from vllm.model_executor.layers.fused_moe.activation import MoEActivation +from vllm.model_executor.layers.fused_moe.config import ( + int4_w4a16_moe_quant_config, +) +from vllm.model_executor.layers.fused_moe.fused_flydsl_moe import fused_flydsl_moe +from vllm.model_executor.layers.quantization.compressed_tensors.compressed_tensors_moe import ( # noqa: E501 + compressed_tensors_moe_w4a16_flydsl, +) +from vllm.platforms import current_platform + +RoutingBuffers = tuple[ + torch.Tensor, # sorted_token_ids + torch.Tensor, # sorted_weights + torch.Tensor, # sorted_expert_ids + torch.Tensor, # num_valid_ids (shape [1], i32) + int, # sorted_size + int, # blocks +] + +MODEL_PARAMS_TO_TUNE = [ + # (num_experts, inter_dim, hidden_size, topk) + (384, 256, 7168, 8), # Kimi K2.5 TP=8 + (384, 512, 7168, 8), # Kimi K2.5 TP=4 +] + +NUM_TOKENS_TO_TUNE = [ + 1, + 2, + 4, + 8, + 16, + 24, + 32, + 48, + 64, + 128, + 256, + 512, + 1024, + 2048, + 4096, + 8192, +] + +TILE_M_SEARCH_SPACE = [16, 32, 64, 128, 256] +TILE_N_SEARCH_SPACE = [16, 32, 64, 128, 256] +TILE_K_SEARCH_SPACE = [16, 32, 64, 128, 256, 512] +TILE_N2_SEARCH_SPACE = [16, 32, 64, 128, 256] +TILE_K2_SEARCH_SPACE = [16, 32, 64, 128, 256, 512] + +TILE_CONFIGS = [] +for tile_m in TILE_M_SEARCH_SPACE: + for tile_n in TILE_N_SEARCH_SPACE: + for tile_k in TILE_K_SEARCH_SPACE: + for tile_n2 in TILE_N2_SEARCH_SPACE: + for tile_k2 in TILE_K2_SEARCH_SPACE: + TILE_CONFIGS.append( + { + "tile_m": tile_m, + "tile_n": tile_n, + "tile_k": tile_k, + "tile_n2": tile_n2, + "tile_k2": tile_k2, + } + ) + + +def tune_flydsl_moe_w4a16( + device: str = "cuda", num_iters: int = 100, num_warmup: int = 10 +): + packed_factor = 8 + w13_num_shards = 2 + params_dtype = torch.bfloat16 + group_size = 32 + scale_factor = 0.01 + + for model_params in MODEL_PARAMS_TO_TUNE: + num_experts = model_params[0] + inter_dim = model_params[1] + hidden_size = model_params[2] + topk = model_params[3] + print( + f"\nTuning: num_experts={num_experts}, inter_dim={inter_dim}, " + f"hidden_size={hidden_size}, topk={topk}...\n" + ) + + w2_scales_size = inter_dim + num_groups_w2 = w2_scales_size // group_size + num_groups_w13 = hidden_size // group_size + + w13_weight = torch.randint( + 0, + 255, + (num_experts, hidden_size // packed_factor, w13_num_shards * inter_dim), + dtype=torch.int32, + device=device, + ) + + w2_weight = torch.randint( + 0, + 255, + (num_experts, inter_dim // packed_factor, hidden_size), + dtype=torch.int32, + device=device, + ) + w13_scale = scale_factor * torch.randn( + num_experts, + num_groups_w13, + w13_num_shards * inter_dim, + dtype=params_dtype, + device=device, + ) + w2_scale = scale_factor * torch.randn( + num_experts, num_groups_w2, hidden_size, dtype=params_dtype, device=device + ) + + w13 = w13_weight + w13 = compressed_tensors_moe_w4a16_flydsl._gptq_int32_to_flydsl_packed(w13) + w13 = w13.view(-1).contiguous() + + w2 = w2_weight + w2 = compressed_tensors_moe_w4a16_flydsl._gptq_int32_to_flydsl_packed(w2) + w2 = w2.view(-1).contiguous() + + w13_scale_flydsl = w13_scale + w2_scale_flydsl = w2_scale + + if group_size > 0 and w13_scale.dim() == 3 and w13_scale.shape[1] > 1: + E, G, N = w13_scale.shape + w13_scale_flydsl = ( + w13_scale_flydsl.view(E, G // 2, 2, N) + .permute(0, 1, 3, 2) + .contiguous() + .view(-1) + .contiguous() + ) + elif w13_scale.dim() == 3 and w13_scale.shape[1] == 1: + w13_scale_flydsl = w13_scale_flydsl.squeeze(1) + + if group_size > 0 and w2_scale.dim() == 3 and w2_scale.shape[1] > 1: + E, G, N = w2_scale.shape + w2_scale_flydsl = ( + w2_scale_flydsl.view(E, G // 2, 2, N) + .permute(0, 1, 3, 2) + .contiguous() + .view(-1) + .contiguous() + ) + elif w2_scale.dim() == 3 and w2_scale.shape[1] == 1: + w2_scale_flydsl = w2_scale_flydsl.squeeze(1) + + w13_scale_flydsl = w13_scale_flydsl.contiguous() + w2_scale_flydsl = w2_scale_flydsl.contiguous() + + w13.is_shuffled = True + w2.is_shuffled = True + + w13_weight_scale = w13_scale.transpose(1, 2).contiguous() + w2_weight_scale = w2_scale.transpose(1, 2).contiguous() + w13_weight_packed = w13_weight.transpose(1, 2).contiguous().view(torch.uint8) + w2_weight_packed = w2_weight.transpose(1, 2).contiguous().view(torch.uint8) + + moe_quant_config = int4_w4a16_moe_quant_config( + w1_scale=w13_weight_scale, + w2_scale=w2_weight_scale, + w1_zp=None, + w2_zp=None, + block_shape=[0, group_size], + ) + + tuned_config = {} + + for num_tokens in NUM_TOKENS_TO_TUNE: + score = torch.rand( + (num_tokens, num_experts), device=device, dtype=torch.float32 + ) + topk_vals, topk_ids = torch.topk(score, k=topk, dim=1) + topk_weights = torch.softmax(topk_vals, dim=1).to(torch.float32) + x = torch.randn( + (num_tokens, hidden_size), dtype=torch.bfloat16, device=device + ) + us_best = float("inf") + for tile_config in TILE_CONFIGS: + try: + tile_m = tile_config["tile_m"] + tile_n = tile_config["tile_n"] + tile_k = tile_config["tile_k"] + tile_n2 = tile_config["tile_n2"] + tile_k2 = tile_config["tile_k2"] + + model_dim = x.shape[1] + assert model_dim % 64 == 0 + assert model_dim % tile_k == 0 + assert inter_dim % tile_n == 0 + assert model_dim % tile_n2 == 0 + assert inter_dim % tile_k2 == 0 + assert ((tile_m * tile_k2) % 256) == 0 + bytes_per_thread_x = (tile_m * tile_k2) // 256 + assert (bytes_per_thread_x % 4) == 0 + + out, _us = run_perftest( + fused_flydsl_moe, + x, + w13, + w2, + num_experts, + inter_dim, + topk_weights, + topk_ids, + num_iters=num_iters, + num_warmup=num_warmup, + w1_scale=w13_scale_flydsl, + w2_scale=w2_scale_flydsl, + topk=topk_weights.shape[-1], + group_size=group_size, + doweight_stage1=False, + scale_is_bf16=True, + config=tile_config, + ) + torch.accelerator.synchronize() + except Exception: + torch.accelerator.synchronize() + continue + else: + us = _us.item() + if us < us_best: + out_ref = fused_experts( + x, + w13_weight_packed, + w2_weight_packed, + topk_weights=topk_weights, + topk_ids=topk_ids, + activation=MoEActivation.SILU, + apply_router_weight_on_input=False, + global_num_experts=num_experts, + expert_map=None, + quant_config=moe_quant_config, + ) + try: + assert torch.allclose(out, out_ref, atol=0.5, rtol=0.1) + except Exception: + continue + else: + print( + f"For [num_tokens={num_tokens}, num_experts={num_experts}, " # noqa: E501 + f"inter_dim={inter_dim}] found new best " # noqa: E501 + f"config={tile_config}, us={us:0.3f}" + ) + us_best = us + tuned_config[str(num_tokens)] = tile_config + device_name = current_platform.get_device_name().replace(" ", "_") + tuned_config_file_name = ( + f"E={num_experts},N={inter_dim},device_name={device_name}," + f"dtype=int4_w4a16,backend=flydsl.json" + ) + tuner_dir_path = os.path.dirname(os.path.realpath(__file__)) + store_path = os.path.join(tuner_dir_path, tuned_config_file_name) + with open(store_path, "w") as f: + json.dump(tuned_config, f, indent=4) + print( + f"\nTuned config for num_tokens={num_tokens} was stored at {store_path}\n" # noqa: E501 + ) + + +if __name__ == "__main__": + tune_flydsl_moe_w4a16(device="cuda") diff --git a/cmake/external_projects/fmha_sm100.cmake b/cmake/external_projects/fmha_sm100.cmake new file mode 100644 index 000000000000..4a2414f5b83c --- /dev/null +++ b/cmake/external_projects/fmha_sm100.cmake @@ -0,0 +1,48 @@ +include(FetchContent) + +# If FMHA_SM100_SRC_DIR is set, fmha_sm100 is installed from that directory +# instead of downloading. This is useful for local MSA development. +if(DEFINED ENV{FMHA_SM100_SRC_DIR}) + set(FMHA_SM100_SRC_DIR $ENV{FMHA_SM100_SRC_DIR}) +endif() + +if(FMHA_SM100_SRC_DIR) + FetchContent_Declare( + fmha_sm100 + SOURCE_DIR ${FMHA_SM100_SRC_DIR} + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + ) +else() + FetchContent_Declare( + fmha_sm100 + GIT_REPOSITORY https://github.com/vllm-project/MSA.git + GIT_TAG 544eee5e09ae2dfa774d5b06739013f9b7402c57 + GIT_PROGRESS TRUE + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + ) +endif() + +FetchContent_GetProperties(fmha_sm100) +if(NOT fmha_sm100_POPULATED) + FetchContent_Populate(fmha_sm100) +endif() +message(STATUS "fmha_sm100 is available at ${fmha_sm100_SOURCE_DIR}") + +add_custom_target(fmha_sm100) + +set(FMHA_SM100_PY_ROOT "${fmha_sm100_SOURCE_DIR}/python/fmha_sm100") + +install(FILES + "${FMHA_SM100_PY_ROOT}/__init__.py" + "${FMHA_SM100_PY_ROOT}/sparse.py" + DESTINATION vllm/third_party/fmha_sm100 + COMPONENT fmha_sm100) + +install(DIRECTORY "${FMHA_SM100_PY_ROOT}/cute/" + DESTINATION vllm/third_party/fmha_sm100/cute + COMPONENT fmha_sm100 + PATTERN "__pycache__" EXCLUDE + PATTERN "*.pyc" EXCLUDE + PATTERN ".git*" EXCLUDE) diff --git a/cmake/external_projects/qutlass.cmake b/cmake/external_projects/qutlass.cmake index 273fe754bed1..66c001919b03 100644 --- a/cmake/external_projects/qutlass.cmake +++ b/cmake/external_projects/qutlass.cmake @@ -32,21 +32,33 @@ endif() message(STATUS "[QUTLASS] QuTLASS is available at ${qutlass_SOURCE_DIR}") if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 13.0) - cuda_archs_loose_intersection(QUTLASS_ARCHS "10.0f;12.0f" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(QUTLASS_SM120_ARCHS "12.0f" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(QUTLASS_SM100_ARCHS "10.0f" "${CUDA_ARCHS}") else() - cuda_archs_loose_intersection(QUTLASS_ARCHS "12.0a;12.1a;10.0a;10.3a" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(QUTLASS_SM120_ARCHS "12.0a;12.1a" "${CUDA_ARCHS}") + cuda_archs_loose_intersection(QUTLASS_SM100_ARCHS "10.0a;10.3a" "${CUDA_ARCHS}") endif() -if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.8 AND QUTLASS_ARCHS) - - if(QUTLASS_ARCHS MATCHES "10\\.(0a|3a|0f)") - set(QUTLASS_TARGET_CC 100) - elseif(QUTLASS_ARCHS MATCHES "12\\.[01][af]?") - set(QUTLASS_TARGET_CC 120) - else() - message(FATAL_ERROR "[QUTLASS] internal error parsing CUDA_ARCHS='${QUTLASS_ARCHS}'.") +# QUTLASS uses TARGET_CUDA_ARCH as a single preprocessor selector for all its +# sources. Do not compile a mixed SM100/SM120 arch list with one selector; prefer +# SM100 when both families are requested because that is the primary deployed +# target for this extension today. +if(QUTLASS_SM100_ARCHS) + set(QUTLASS_ARCHS "${QUTLASS_SM100_ARCHS}") + set(QUTLASS_TARGET_CC 100) + if(QUTLASS_SM120_ARCHS) + message(WARNING + "[QUTLASS] Both SM100 and SM120 archs were requested; selecting SM100 " + "because TARGET_CUDA_ARCH is a single compile-time selector.") endif() +elseif(QUTLASS_SM120_ARCHS) + set(QUTLASS_ARCHS "${QUTLASS_SM120_ARCHS}") + set(QUTLASS_TARGET_CC 120) +else() + set(QUTLASS_ARCHS) +endif() +if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 12.8 AND QUTLASS_ARCHS) set(QUTLASS_SOURCES ${qutlass_SOURCE_DIR}/qutlass/csrc/bindings.cpp ${qutlass_SOURCE_DIR}/qutlass/csrc/gemm.cu diff --git a/cmake/utils.cmake b/cmake/utils.cmake index dd2034c1c5ee..e3e766541df1 100644 --- a/cmake/utils.cmake +++ b/cmake/utils.cmake @@ -487,9 +487,9 @@ endfunction() function(cuda_archs_sm90plus OUT_CUDA_ARCHS TGT_CUDA_ARCHS) if(${CMAKE_CUDA_COMPILER_VERSION} VERSION_GREATER_EQUAL 13.0) - cuda_archs_loose_intersection(_archs "9.0a;10.0f;11.0f" "${TGT_CUDA_ARCHS}") + cuda_archs_loose_intersection(_archs "9.0a;10.0f;11.0f;12.0f" "${TGT_CUDA_ARCHS}") else() - cuda_archs_loose_intersection(_archs "9.0a;10.0a;10.1a;10.3a" "${TGT_CUDA_ARCHS}") + cuda_archs_loose_intersection(_archs "9.0a;10.0a;10.1a;10.3a;12.0a;12.1a" "${TGT_CUDA_ARCHS}") endif() set(${OUT_CUDA_ARCHS} ${_archs} PARENT_SCOPE) endfunction() diff --git a/csrc/cpu/cpu_attn.cpp b/csrc/cpu/cpu_attn.cpp index 26b881f4f143..2634e649a719 100644 --- a/csrc/cpu/cpu_attn.cpp +++ b/csrc/cpu/cpu_attn.cpp @@ -15,9 +15,10 @@ torch::Tensor get_scheduler_metadata( const int64_t num_req, const int64_t num_heads_q, const int64_t num_heads_kv, const int64_t head_dim, const torch::Tensor& seq_lens, at::ScalarType dtype, - const torch::Tensor& query_start_loc, const bool casual, + const torch::Tensor& query_start_loc, const bool causal, const int64_t window_size, const std::string& isa_hint, - const bool enable_kv_split) { + const bool enable_kv_split, + const std::optional& dynamic_causal) { cpu_attention::ISA isa; if (isa_hint == "amx") { isa = cpu_attention::ISA::AMX; @@ -44,24 +45,13 @@ torch::Tensor get_scheduler_metadata( input.head_dim = head_dim; input.query_start_loc = query_start_loc.data_ptr(); input.seq_lens = seq_lens.data_ptr(); - if (window_size != -1) { - input.left_sliding_window_size = window_size - 1; - if (casual) { - input.right_sliding_window_size = 0; - } else { - input.right_sliding_window_size = window_size - 1; - } - } else { - input.left_sliding_window_size = -1; - if (casual) { - input.right_sliding_window_size = 0; - } else { - input.right_sliding_window_size = -1; - } - } - input.casual = casual; + + input.sliding_window_size = window_size; + input.causal = causal; input.isa = isa; input.enable_kv_split = enable_kv_split; + input.dynamic_causal = + dynamic_causal.has_value() ? dynamic_causal->data_ptr() : nullptr; VLLM_DISPATCH_FLOATING_TYPES(dtype, "get_scheduler_metadata", [&]() { CPU_ATTN_DISPATCH(head_dim, isa, 0, [&]() { @@ -175,10 +165,11 @@ void cpu_attention_with_kv_cache( const torch::Tensor& seq_lens, // [num_tokens] const double scale, const bool causal, const std::optional& alibi_slopes, // [num_heads] - const int64_t sliding_window_left, const int64_t sliding_window_right, + const int64_t sliding_window, const torch::Tensor& block_table, // [num_tokens, max_block_num] const double softcap, const torch::Tensor& scheduler_metadata, - const std::optional& s_aux, // [num_heads] + const std::optional& s_aux, // [num_heads] + const std::optional& dynamic_causal, // [num_reqs] const double k_scale = 1.0, const double v_scale = 1.0, const std::string& kv_cache_dtype = "auto") { TORCH_CHECK_EQ(query.dim(), 3); @@ -220,13 +211,11 @@ void cpu_attention_with_kv_cache( input.alibi_slopes = alibi_slopes.has_value() ? alibi_slopes->data_ptr() : nullptr; input.s_aux = s_aux.has_value() ? s_aux->data_ptr() : nullptr; + input.dynamic_causal = + dynamic_causal.has_value() ? dynamic_causal->data_ptr() : nullptr; input.scale = scale; input.causal = causal; - input.sliding_window_left = sliding_window_left; - input.sliding_window_right = sliding_window_right; - if (input.causal) { - input.sliding_window_right = 0; - } + input.sliding_window_size = sliding_window; input.softcap = static_cast(softcap); if (is_fp8) { diff --git a/csrc/cpu/cpu_attn_impl.hpp b/csrc/cpu/cpu_attn_impl.hpp index 70081b36ee5b..d1b6c71c1829 100644 --- a/csrc/cpu/cpu_attn_impl.hpp +++ b/csrc/cpu/cpu_attn_impl.hpp @@ -388,13 +388,13 @@ class AttentionScheduler { int32_t head_dim; int32_t* query_start_loc; int32_t* seq_lens; - int32_t left_sliding_window_size; - int32_t right_sliding_window_size; - bool casual; + int32_t sliding_window_size; + bool causal; cpu_attention::ISA isa; int32_t max_num_q_per_iter; // max Q head num can be hold in registers int32_t kv_block_alignment; // context length alignment requirement bool enable_kv_split; + bool* dynamic_causal; }; static constexpr int32_t MaxQTileIterNum = 128; @@ -403,7 +403,8 @@ class AttentionScheduler { : available_cache_size_(cpu_utils::get_available_l2_size()) {} torch::Tensor schedule(const ScheduleInput& input) const { - const bool casual = input.casual; + const bool causal = input.causal; + const bool is_dynamic_causal = input.dynamic_causal != nullptr; const int32_t thread_num = omp_get_max_threads(); const int64_t cache_size = cpu_utils::get_available_l2_size(); const int32_t max_num_q_per_iter = input.max_num_q_per_iter; @@ -434,8 +435,7 @@ class AttentionScheduler { const int32_t default_tile_token_num = default_tile_size / q_head_per_kv; const int32_t split_kv_q_token_num_threshold = input.enable_kv_split ? 1 : 0; - const int32_t left_sliding_window_size = input.left_sliding_window_size; - const int32_t right_sliding_window_size = input.right_sliding_window_size; + const int32_t sliding_window_size = input.sliding_window_size; TORCH_CHECK_LE(split_kv_q_token_num_threshold * q_head_per_kv, 16); // get total kv len @@ -444,7 +444,9 @@ class AttentionScheduler { const int32_t seq_len = input.seq_lens[req_id]; const int32_t q_token_num = input.query_start_loc[req_id + 1] - input.query_start_loc[req_id]; - const int32_t q_start_pos = (casual ? (seq_len - q_token_num) : 0); + const bool req_causal = + is_dynamic_causal ? input.dynamic_causal[req_id] : causal; + const int32_t q_start_pos = seq_len - q_token_num; const int32_t kv_start_pos = 0; const int32_t kv_end_pos = seq_len; @@ -456,7 +458,7 @@ class AttentionScheduler { const int32_t q_tile_pos_right = q_tile_pos_left + q_tile_token_num; const auto [kv_tile_pos_left, kv_tile_pos_right] = calcu_kv_tile_pos( kv_start_pos, kv_end_pos, q_tile_pos_left, q_tile_pos_right, - left_sliding_window_size, right_sliding_window_size); + sliding_window_size, req_causal); const auto [aligned_kv_tile_pos_left, aligned_kv_tile_pos_right] = align_kv_tile_pos(kv_tile_pos_left, kv_tile_pos_right, kv_len_alignment); @@ -484,7 +486,9 @@ class AttentionScheduler { const int32_t seq_len = input.seq_lens[req_id]; const int32_t q_token_num = input.query_start_loc[req_id + 1] - input.query_start_loc[req_id]; - const int32_t q_start_pos = (casual ? (seq_len - q_token_num) : 0); + const bool req_causal = + is_dynamic_causal ? input.dynamic_causal[req_id] : causal; + const int32_t q_start_pos = seq_len - q_token_num; const int32_t kv_start_pos = 0; const int32_t kv_end_pos = seq_len; int32_t local_split_id = 0; @@ -498,7 +502,7 @@ class AttentionScheduler { const int32_t q_tile_pos_right = q_tile_pos_left + q_tile_token_num; const auto [kv_tile_pos_left, kv_tile_pos_right] = calcu_kv_tile_pos( kv_start_pos, kv_end_pos, q_tile_pos_left, q_tile_pos_right, - left_sliding_window_size, right_sliding_window_size); + sliding_window_size, req_causal); const auto [aligned_kv_tile_pos_left, aligned_kv_tile_pos_right] = align_kv_tile_pos(kv_tile_pos_left, kv_tile_pos_right, kv_len_alignment); @@ -708,15 +712,41 @@ class AttentionScheduler { return metadata_tensor; } + FORCE_INLINE static std::pair calcu_sliding_window_size( + int32_t window_size, bool causal) { + int32_t left_sliding_window_size, right_sliding_window_size; + if (window_size != -1) { + left_sliding_window_size = window_size - 1; + if (causal) { + right_sliding_window_size = 0; + } else { + right_sliding_window_size = window_size - 1; + } + } else { + left_sliding_window_size = -1; + if (causal) { + right_sliding_window_size = 0; + } else { + right_sliding_window_size = -1; + } + } + + return {left_sliding_window_size, right_sliding_window_size}; + } + FORCE_INLINE static std::pair calcu_kv_tile_pos( int32_t kv_left_pos, int32_t kv_right_pos, int32_t q_left_pos, - int32_t q_right_pos, int32_t sliding_window_left, - int32_t sliding_window_right) { - if (sliding_window_left != -1) { - kv_left_pos = std::max(kv_left_pos, q_left_pos - sliding_window_left); + int32_t q_right_pos, int32_t window_size, bool causal) { + auto [left_sliding_window_size, right_sliding_window_size] = + calcu_sliding_window_size(window_size, causal); + + if (left_sliding_window_size != -1) { + kv_left_pos = + std::max(kv_left_pos, q_left_pos - left_sliding_window_size); } - if (sliding_window_right != -1) { - kv_right_pos = std::min(kv_right_pos, q_right_pos + sliding_window_right); + if (right_sliding_window_size != -1) { + kv_right_pos = + std::min(kv_right_pos, q_right_pos + right_sliding_window_size); } return {kv_left_pos, kv_right_pos}; } @@ -805,10 +835,10 @@ struct AttentionInput { int32_t* block_table; float* alibi_slopes; c10::BFloat16* s_aux; + bool* dynamic_causal; float scale; bool causal; - int32_t sliding_window_left; - int32_t sliding_window_right; + int32_t sliding_window_size; float softcap; // FP8 KV cache scales (used by FP8 attention implementations) float k_scale_fp8 = 1.0f; @@ -822,8 +852,8 @@ struct AttentionInput { logits_buffer_t *__restrict__ logits_buffer, \ float *__restrict__ partial_q_buffer, float *__restrict__ max_buffer, \ float *__restrict__ sum_buffer, int32_t *__restrict__ block_table, \ - const int32_t kv_tile_start_pos, const int32_t kv_tile_end_pos, \ - const int32_t kv_tile_token_num, \ + const int32_t kv_end_pos, const int32_t kv_tile_start_pos, \ + const int32_t kv_tile_end_pos, const int32_t kv_tile_token_num, \ const int64_t kv_cache_num_blocks_stride, const int32_t q_head_num, \ const int32_t q_token_num, const int32_t q_tile_start_pos, \ const int32_t q_heads_per_kv, const int32_t block_size, \ @@ -834,7 +864,7 @@ struct AttentionInput { #define CPU_ATTENTION_PARAMS \ q_heads_buffer, k_head_cache_ptr, v_head_cache_ptr, logits_buffer, \ - partial_q_buffer, max_buffer, sum_buffer, block_table, \ + partial_q_buffer, max_buffer, sum_buffer, block_table, kv_end_pos, \ kv_tile_start_pos, kv_tile_end_pos, kv_tile_token_num, \ kv_cache_num_blocks_stride, q_head_num, q_token_num, q_tile_start_pos, \ q_heads_per_kv, block_size, left_window_size, right_window_size, scale, \ @@ -917,6 +947,7 @@ class AttentionMainLoop { // - max_buffer: [MaxQHeadNumPerIteration, 1], store max logits // - sum_buffer: [MaxQHeadNumPerIteration, 1], store sum of exp // - block_table + // - kv_end_pos: un-aligned end position of KV cache // - kv_tile_start_pos: start position of KV cache, aligned to // BlockSizeAlignment // - kv_tile_end_pos: end position of KV cache, aligned to @@ -1043,7 +1074,7 @@ class AttentionMainLoop { } apply_mask(logits_buffer, kv_tile_token_num, q_tile_start_pos, - kv_tile_start_pos, kv_tile_end_pos, q_token_num, + kv_end_pos, kv_tile_start_pos, kv_tile_end_pos, q_token_num, q_heads_per_kv, left_window_size, right_window_size); // if (debug_info){ @@ -1126,7 +1157,7 @@ class AttentionMainLoop { void apply_mask(logits_buffer_t* __restrict__ logits_buffer, const int64_t logits_buffer_stride, - const int32_t q_tile_start_pos, + const int32_t q_tile_start_pos, const int32_t kv_end_pos, const int32_t kv_tile_start_pos, const int32_t kv_tile_end_pos, const int32_t q_token_num, const int32_t q_heads_per_kv, @@ -1154,7 +1185,7 @@ class AttentionMainLoop { std::max(kv_tile_start_pos, curr_token_pos + sliding_window_right + 1)); } - return pos; + return std::min(pos, kv_end_pos); }(); int32_t left_invalid_token_num = left_kv_pos - kv_tile_start_pos; @@ -1441,15 +1472,16 @@ class AttentionMainLoop { const int64_t q_head_num_stride = input->query_num_heads_stride; const int64_t kv_cache_head_num_stride = input->cache_num_kv_heads_stride; const int64_t kv_cache_block_num_stride = input->cache_num_blocks_stride; - const int32_t sliding_window_left = input->sliding_window_left; - const int32_t sliding_window_right = input->sliding_window_right; + const int32_t sliding_window_size = input->sliding_window_size; const int32_t block_size = input->block_size; const float scale = input->scale; const float softcap_scale = input->softcap; const float* alibi_slopes = input->alibi_slopes; const c10::BFloat16* s_aux = input->s_aux; + const bool* dynamic_causal = input->dynamic_causal; + const bool is_dynamic_causal = dynamic_causal != nullptr; - const bool casual = input->causal; + const bool causal = input->causal; int32_t* const block_table = input->block_table; const int64_t block_table_stride = input->blt_num_tokens_stride; @@ -1532,6 +1564,11 @@ class AttentionMainLoop { &curr_workitem_groups[workitem_group_idx]; const int32_t current_group_idx = current_workitem_group->req_id; + const int32_t current_group_causal = + is_dynamic_causal ? dynamic_causal[current_group_idx] : causal; + auto [sliding_window_left, sliding_window_right] = + AttentionScheduler::calcu_sliding_window_size( + sliding_window_size, current_group_causal); const int32_t kv_start_pos = current_workitem_group->kv_split_pos_start; const int32_t kv_end_pos = current_workitem_group->kv_split_pos_end; @@ -1559,8 +1596,7 @@ class AttentionMainLoop { const int32_t q_end = input->query_start_loc[current_group_idx + 1]; const int32_t q_start = input->query_start_loc[current_group_idx]; const int32_t seq_len = input->seq_lens[current_group_idx]; - const int32_t q_start_pos = - (casual ? seq_len - (q_end - q_start) : 0); + const int32_t q_start_pos = seq_len - (q_end - q_start); const int32_t block_num = (seq_len + block_size - 1) / block_size; // Only apply sink for the first KV split bool use_sink = (s_aux != nullptr && @@ -1610,8 +1646,8 @@ class AttentionMainLoop { const auto [kv_tile_start_pos, kv_tile_end_pos] = AttentionScheduler::calcu_kv_tile_pos( kv_start_pos, kv_end_pos, q_tile_start_pos, - q_tile_end_pos, sliding_window_left, - sliding_window_right); + q_tile_end_pos, sliding_window_size, + current_group_causal); const auto [rounded_kv_tile_start_pos, rounded_kv_tile_end_pos] = AttentionScheduler::align_kv_tile_pos( kv_tile_start_pos, kv_tile_end_pos, blocksize_alignment); @@ -1724,8 +1760,8 @@ class AttentionMainLoop { actual_kv_tile_pos_right] = AttentionScheduler::calcu_kv_tile_pos( kv_tile_pos_left, kv_tile_pos_right, q_tile_pos_left, - q_tile_pos_right, sliding_window_left, - sliding_window_right); + q_tile_pos_right, sliding_window_size, + current_group_causal); const int32_t q_iter_idx = q_head_tile_token_offset / curr_max_q_token_num_per_iter; @@ -1789,7 +1825,7 @@ class AttentionMainLoop { attn_impl.template execute_attention( curr_q_heads_buffer, curr_k_cache, curr_v_cache, logits_buffer, curr_partial_q_buffer, curr_max_buffer, - curr_sum_buffer, curr_block_table, + curr_sum_buffer, curr_block_table, kv_end_pos, aligned_actual_kv_tile_pos_left, aligned_actual_kv_tile_pos_right, actual_kv_token_num, kv_cache_block_num_stride, q_tile_head_num, diff --git a/csrc/cpu/cpu_fused_moe.cpp b/csrc/cpu/cpu_fused_moe.cpp index 5839d6c2aaf3..c0d92bde77bb 100644 --- a/csrc/cpu/cpu_fused_moe.cpp +++ b/csrc/cpu/cpu_fused_moe.cpp @@ -1,3 +1,5 @@ +#include + #include "cpu/cpu_types.hpp" #include "cpu/utils.hpp" #include "cpu/micro_gemm/cpu_micro_gemm_vec.hpp" @@ -163,7 +165,6 @@ void gelu_tanh_and_mul(float* __restrict__ input, scalar_t* __restrict__ output, vec_op::FP32Vec16 w1_vec(0.7978845608028654); vec_op::FP32Vec16 w2_vec(0.5); vec_op::FP32Vec16 w3_vec(0.044715); - alignas(64) float temp[16]; for (int32_t m = 0; m < m_size; ++m) { for (int32_t n = 0; n < dim; n += 16) { @@ -171,12 +172,9 @@ void gelu_tanh_and_mul(float* __restrict__ input, scalar_t* __restrict__ output, vec_op::FP32Vec16 up_vec(up + n); auto gate_pow3_vec = gate_vec * gate_vec * gate_vec; auto inner_vec = w1_vec * (gate_vec + w3_vec * gate_pow3_vec); - - inner_vec.save(temp); - for (int32_t i = 0; i < 16; ++i) { - temp[i] = std::tanh(temp[i]); - } - vec_op::FP32Vec16 tanh_vec(temp); + // Note: can't use fast_exp form because diffusiongemma will generate + // wrong results + vec_op::FP32Vec16 tanh_vec(Sleef_tanhf16_u10(inner_vec.reg)); auto gelu_tanh = gate_vec * w2_vec * (one_vec + tanh_vec); auto gated_output_fp32 = up_vec * gelu_tanh; scalar_vec_t gated_output = scalar_vec_t(gated_output_fp32); diff --git a/csrc/cpu/generate_cpu_attn_dispatch.py b/csrc/cpu/generate_cpu_attn_dispatch.py index 7c7123a6def5..95ce9e66927e 100644 --- a/csrc/cpu/generate_cpu_attn_dispatch.py +++ b/csrc/cpu/generate_cpu_attn_dispatch.py @@ -11,7 +11,7 @@ HEAD_DIMS_32 = [32, 64, 96, 128, 160, 192, 224, 256, 512] # Head dimensions divisible by 16 but not 32 (VEC16 only) -HEAD_DIMS_16 = [80, 112] +HEAD_DIMS_16 = [48, 80, 112] # ISA types ISA_TYPES = { diff --git a/csrc/cpu/layernorm.cpp b/csrc/cpu/layernorm.cpp index a76ad08928a2..704fb146338e 100644 --- a/csrc/cpu/layernorm.cpp +++ b/csrc/cpu/layernorm.cpp @@ -4,8 +4,9 @@ namespace { template void rms_norm_impl(scalar_t* __restrict__ out, const scalar_t* __restrict__ input, - const scalar_t* __restrict__ weight, const float epsilon, - const int num_tokens, const int hidden_size) { + const scalar_t* __restrict__ weight, const bool has_weight, + const float epsilon, const int num_tokens, + const int hidden_size) { using scalar_vec_t = vec_op::vec_t; constexpr int VEC_ELEM_NUM = scalar_vec_t::get_elem_num(); TORCH_CHECK(hidden_size % VEC_ELEM_NUM == 0); @@ -27,12 +28,15 @@ void rms_norm_impl(scalar_t* __restrict__ out, for (int j = 0; j < hidden_size; j += VEC_ELEM_NUM) { scalar_vec_t x(input_p + j); - scalar_vec_t w(weight + j); - vec_op::FP32Vec8 fp32_x(x); - vec_op::FP32Vec8 fp32_w(w); - - vec_op::FP32Vec8 fp32_out = fp32_x * fp32_s_variance * fp32_w; + vec_op::FP32Vec8 fp32_out; + if (has_weight) { + scalar_vec_t w(weight + j); + vec_op::FP32Vec8 fp32_w(w); + fp32_out = fp32_x * fp32_s_variance * fp32_w; + } else { + fp32_out = fp32_x * fp32_s_variance; + } scalar_vec_t out(fp32_out); out.save(output_p + j); @@ -44,8 +48,8 @@ template void fused_add_rms_norm_impl(scalar_t* __restrict__ input, scalar_t* __restrict__ residual, const scalar_t* __restrict__ weight, - const float epsilon, const int num_tokens, - const int hidden_size) { + const bool has_weight, const float epsilon, + const int num_tokens, const int hidden_size) { using scalar_vec_t = vec_op::vec_t; constexpr int VEC_ELEM_NUM = scalar_vec_t::get_elem_num(); TORCH_CHECK(hidden_size % VEC_ELEM_NUM == 0); @@ -72,13 +76,18 @@ void fused_add_rms_norm_impl(scalar_t* __restrict__ input, vec_op::FP32Vec8 fp32_s_variance(s_variance); for (int j = 0; j < hidden_size; j += VEC_ELEM_NUM) { - scalar_vec_t w(weight + j); - scalar_vec_t res(residual_p + j); - - vec_op::FP32Vec8 fp32_w(w); - vec_op::FP32Vec8 fp32_res(res); - - vec_op::FP32Vec8 fp32_out = fp32_res * fp32_s_variance * fp32_w; + vec_op::FP32Vec8 fp32_out; + if (has_weight) { + scalar_vec_t w(weight + j); + scalar_vec_t res(residual_p + j); + vec_op::FP32Vec8 fp32_w(w); + vec_op::FP32Vec8 fp32_res(res); + fp32_out = fp32_res * fp32_s_variance * fp32_w; + } else { + scalar_vec_t res(residual_p + j); + vec_op::FP32Vec8 fp32_res(res); + fp32_out = fp32_res * fp32_s_variance; + } scalar_vec_t out(fp32_out); out.save(input_p + j); @@ -87,31 +96,41 @@ void fused_add_rms_norm_impl(scalar_t* __restrict__ input, } } // namespace -void rms_norm(torch::Tensor& out, torch::Tensor& input, torch::Tensor& weight, - double epsilon) { +void rms_norm(torch::Tensor& out, torch::Tensor& input, + std::optional weight, double epsilon) { int hidden_size = input.size(-1); int num_tokens = input.numel() / hidden_size; + const bool has_weight = weight.has_value(); + if (has_weight) { + TORCH_CHECK(weight->is_contiguous()); + } VLLM_DISPATCH_FLOATING_TYPES(input.scalar_type(), "rms_norm_impl", [&] { CPU_KERNEL_GUARD_IN(rms_norm_impl) rms_norm_impl(out.data_ptr(), input.data_ptr(), - weight.data_ptr(), epsilon, num_tokens, - hidden_size); + has_weight ? weight->data_ptr() : nullptr, + has_weight, epsilon, num_tokens, hidden_size); CPU_KERNEL_GUARD_OUT(rms_norm_impl) }); } void fused_add_rms_norm(torch::Tensor& input, torch::Tensor& residual, - torch::Tensor& weight, double epsilon) { + std::optional weight, double epsilon) { int hidden_size = input.size(-1); int num_tokens = input.numel() / hidden_size; + const bool has_weight = weight.has_value(); + if (has_weight) { + TORCH_CHECK(weight->scalar_type() == input.scalar_type()); + TORCH_CHECK(weight->is_contiguous()); + } VLLM_DISPATCH_FLOATING_TYPES( input.scalar_type(), "fused_add_rms_norm_impl", [&] { CPU_KERNEL_GUARD_IN(fused_add_rms_norm_impl) fused_add_rms_norm_impl( input.data_ptr(), residual.data_ptr(), - weight.data_ptr(), epsilon, num_tokens, hidden_size); + has_weight ? weight->data_ptr() : nullptr, has_weight, + epsilon, num_tokens, hidden_size); CPU_KERNEL_GUARD_OUT(fused_add_rms_norm_impl) }); } diff --git a/csrc/cpu/torch_bindings.cpp b/csrc/cpu/torch_bindings.cpp index 495185769ba6..2aad5e2387db 100644 --- a/csrc/cpu/torch_bindings.cpp +++ b/csrc/cpu/torch_bindings.cpp @@ -152,7 +152,8 @@ torch::Tensor get_scheduler_metadata( const torch::Tensor& seq_lens, at::ScalarType dtype, const torch::Tensor& query_start_loc, const bool casual, const int64_t window_size, const std::string& isa_hint, - const bool enable_kv_split); + const bool enable_kv_split, + const std::optional& dynamic_causal); void cpu_attn_reshape_and_cache(const torch::Tensor& key, const torch::Tensor& value, @@ -169,10 +170,10 @@ void cpu_attention_with_kv_cache( const torch::Tensor& query_start_loc, const torch::Tensor& seq_lens, const double scale, const bool causal, const std::optional& alibi_slopes, - const int64_t sliding_window_left, const int64_t sliding_window_right, - const torch::Tensor& block_table, const double softcap, - const torch::Tensor& scheduler_metadata, - const std::optional& s_aux, const double k_scale, + const int64_t sliding_window_left, const torch::Tensor& block_table, + const double softcap, const torch::Tensor& scheduler_metadata, + const std::optional& s_aux, + const std::optional& dynamic_causal, const double k_scale, const double v_scale, const std::string& kv_cache_dtype); // Note: just for avoiding importing errors @@ -309,13 +310,13 @@ TORCH_LIBRARY_EXPAND(TORCH_EXTENSION_NAME, ops) { // Layernorm // Apply Root Mean Square (RMS) Normalization to the input tensor. ops.def( - "rms_norm(Tensor! out, Tensor input, Tensor weight, float epsilon) -> " + "rms_norm(Tensor! out, Tensor input, Tensor? weight, float epsilon) -> " "()"); ops.impl("rms_norm", torch::kCPU, &rms_norm); // In-place fused Add and RMS Normalization. ops.def( - "fused_add_rms_norm(Tensor! input, Tensor! residual, Tensor weight, " + "fused_add_rms_norm(Tensor! input, Tensor! residual, Tensor? weight, " "float epsilon) -> ()"); ops.impl("fused_add_rms_norm", torch::kCPU, &fused_add_rms_norm); @@ -500,7 +501,7 @@ TORCH_LIBRARY_EXPAND(TORCH_EXTENSION_NAME, ops) { "get_scheduler_metadata(int num_req, int num_heads_q, int num_heads_kv, " "int head_dim, Tensor seq_lens, ScalarType dtype, Tensor " "query_start_loc, bool casual, int window_size, str isa_hint, bool " - "enable_kv_split) -> Tensor", + "enable_kv_split, Tensor? dynamic_causal) -> Tensor", &get_scheduler_metadata); ops.def( "cpu_attn_reshape_and_cache(Tensor key, Tensor value, Tensor(a2!) " @@ -512,8 +513,9 @@ TORCH_LIBRARY_EXPAND(TORCH_EXTENSION_NAME, ops) { "cpu_attention_with_kv_cache(Tensor query, Tensor key_cache, Tensor " "value_cache, Tensor(a3!) output, Tensor query_start_loc, Tensor " "seq_lens, float scale, bool causal, Tensor? alibi_slopes, SymInt " - "sliding_window_left, SymInt sliding_window_right, Tensor block_table, " - "float softcap, Tensor scheduler_metadata, Tensor? s_aux, " + "sliding_window_size, Tensor block_table, " + "float softcap, Tensor scheduler_metadata, Tensor? s_aux, Tensor? " + "dynamic_causal, " "float k_scale=1.0, float v_scale=1.0, str kv_cache_dtype=\"auto\") -> " "()", &cpu_attention_with_kv_cache); diff --git a/csrc/cutlass_extensions/vllm_cutlass_library_extension.py b/csrc/cutlass_extensions/vllm_cutlass_library_extension.py index 34fb64c413db..d692502f3ffd 100644 --- a/csrc/cutlass_extensions/vllm_cutlass_library_extension.py +++ b/csrc/cutlass_extensions/vllm_cutlass_library_extension.py @@ -57,13 +57,13 @@ class MixedInputKernelScheduleType(enum.Enum): } VLLMDataTypeTorchDataTypeTag: dict[VLLMDataType | DataType, str] = { - DataType.u8: "at::ScalarType::Byte", - DataType.s8: "at::ScalarType::Char", - DataType.e4m3: "at::ScalarType::Float8_e4m3fn", - DataType.s32: "at::ScalarType::Int", - DataType.f16: "at::ScalarType::Half", - DataType.bf16: "at::ScalarType::BFloat16", - DataType.f32: "at::ScalarType::Float", + DataType.u8: "torch::headeronly::ScalarType::Byte", + DataType.s8: "torch::headeronly::ScalarType::Char", + DataType.e4m3: "torch::headeronly::ScalarType::Float8_e4m3fn", + DataType.s32: "torch::headeronly::ScalarType::Int", + DataType.f16: "torch::headeronly::ScalarType::Half", + DataType.bf16: "torch::headeronly::ScalarType::BFloat16", + DataType.f32: "torch::headeronly::ScalarType::Float", } VLLMKernelScheduleTag: dict[MixedInputKernelScheduleType | KernelScheduleType, str] = { diff --git a/csrc/libtorch_stable/activation_kernels.cu b/csrc/libtorch_stable/activation_kernels.cu index cdab456348e2..e1dc01346055 100644 --- a/csrc/libtorch_stable/activation_kernels.cu +++ b/csrc/libtorch_stable/activation_kernels.cu @@ -10,11 +10,20 @@ namespace vllm { -template __device__ __forceinline__ scalar_t compute(const scalar_t& x, const scalar_t& y, - const float limit) { + const float limit, + const float alpha, + const float beta) { if constexpr (act_first) { scalar_t gate = x; scalar_t up = y; @@ -22,7 +31,9 @@ __device__ __forceinline__ scalar_t compute(const scalar_t& x, gate = (scalar_t)fminf((float)gate, limit); up = (scalar_t)fmaxf(fminf((float)up, limit), -limit); } - return ACT_FN(gate) * up; + // act_first: gate is the activated half -> alpha applies to gate; + // beta is added to up (the non-activated half). + return (scalar_t)(ACT_FN(gate, alpha) * ((float)up + beta)); } else { scalar_t gate = x; scalar_t up = y; @@ -30,55 +41,68 @@ __device__ __forceinline__ scalar_t compute(const scalar_t& x, gate = (scalar_t)fmaxf(fminf((float)gate, limit), -limit); up = (scalar_t)fminf((float)up, limit); } - return gate * ACT_FN(up); + // !act_first: up is the activated half -> alpha applies to up; + // beta is added to gate (the non-activated half). + return (scalar_t)(((float)gate + beta) * ACT_FN(up, alpha)); } } -template __device__ __forceinline__ packed_t packed_compute(const packed_t& x, const packed_t& y, - const float limit) { + const float limit, + const float alpha, + const float beta) { if constexpr (act_first) { packed_t gate = x; packed_t up = y; + float2 u = cast_to_float2(up); if constexpr (HAS_CLAMP) { float2 g = cast_to_float2(gate); - float2 u = cast_to_float2(up); g.x = fminf(g.x, limit); g.y = fminf(g.y, limit); u.x = fmaxf(fminf(u.x, limit), -limit); u.y = fmaxf(fminf(u.y, limit), -limit); gate = cast_to_packed(g); - up = cast_to_packed(u); } - return packed_mul(PACKED_ACT_FN(gate), up); + // act_first: gate is the activated half -> alpha applies to gate; + // beta is added to up (the non-activated half). + float2 activated = cast_to_float2(PACKED_ACT_FN(gate, alpha)); + activated.x *= u.x + beta; + activated.y *= u.y + beta; + return cast_to_packed(activated); } else { packed_t gate = x; packed_t up = y; + float2 g = cast_to_float2(gate); if constexpr (HAS_CLAMP) { - float2 g = cast_to_float2(gate); float2 u = cast_to_float2(up); g.x = fmaxf(fminf(g.x, limit), -limit); g.y = fmaxf(fminf(g.y, limit), -limit); u.x = fminf(u.x, limit); u.y = fminf(u.y, limit); - gate = cast_to_packed(g); up = cast_to_packed(u); } - return packed_mul(gate, PACKED_ACT_FN(up)); + // !act_first: up is the activated half -> alpha applies to up; + // beta is added to gate (the non-activated half). + float2 activated = cast_to_float2(PACKED_ACT_FN(up, alpha)); + activated.x *= g.x + beta; + activated.y *= g.y + beta; + return cast_to_packed(activated); } } // Activation and gating kernel template. template + scalar_t (*ACT_FN)(const scalar_t&, const float), + packed_t (*PACKED_ACT_FN)(const packed_t&, const float), + bool act_first, bool use_vec, bool HAS_CLAMP, bool use_256b = false> __global__ void act_and_mul_kernel( scalar_t* __restrict__ out, // [..., d] const scalar_t* __restrict__ input, // [..., 2, d] - const int d, const float limit) { + const int d, const float limit, const float alpha, const float beta) { const scalar_t* x_ptr = input + blockIdx.x * 2 * d; const scalar_t* y_ptr = x_ptr + d; scalar_t* out_ptr = out + blockIdx.x * d; @@ -105,7 +129,7 @@ __global__ void act_and_mul_kernel( for (int j = 0; j < pvec_t::NUM_ELTS; j++) { x.elts[j] = packed_compute( - x.elts[j], y.elts[j], limit); + x.elts[j], y.elts[j], limit, alpha, beta); } if constexpr (use_256b) { st256(x, &out_vec[i]); @@ -118,29 +142,34 @@ __global__ void act_and_mul_kernel( for (int64_t idx = threadIdx.x; idx < d; idx += blockDim.x) { const scalar_t x = VLLM_LDG(&x_ptr[idx]); const scalar_t y = VLLM_LDG(&y_ptr[idx]); - out_ptr[idx] = - compute(x, y, limit); + out_ptr[idx] = compute( + x, y, limit, alpha, beta); } } } +// Gated activations take an `alpha` argument that scales the sigmoid input +// (`x * sigmoid(alpha * x)`). alpha defaults to 1.0 at all call sites, which +// is exactly SiLU; only the clamp path (silu_and_mul_with_clamp) passes a +// non-default alpha. Activations that do not use alpha simply ignore it. template -__device__ __forceinline__ T silu_kernel(const T& x) { - // x * sigmoid(x) - return (T)(((float)x) / (1.0f + expf((float)-x))); +__device__ __forceinline__ T silu_kernel(const T& x, const float alpha) { + // x * sigmoid(alpha * x) + return (T)(((float)x) / (1.0f + expf((float)-x * alpha))); } template -__device__ __forceinline__ packed_t packed_silu_kernel(const packed_t& val) { - // x * sigmoid(x) +__device__ __forceinline__ packed_t packed_silu_kernel(const packed_t& val, + const float alpha) { + // x * sigmoid(alpha * x) float2 fval = cast_to_float2(val); - fval.x = fval.x / (1.0f + expf(-fval.x)); - fval.y = fval.y / (1.0f + expf(-fval.y)); + fval.x = fval.x / (1.0f + expf(-fval.x * alpha)); + fval.y = fval.y / (1.0f + expf(-fval.y * alpha)); return cast_to_packed(fval); } template -__device__ __forceinline__ T gelu_kernel(const T& x) { +__device__ __forceinline__ T gelu_kernel(const T& x, const float /*alpha*/) { // Equivalent to PyTorch GELU with 'none' approximation. // Refer to: // https://github.com/pytorch/pytorch/blob/8ac9b20d4b090c213799e81acf48a55ea8d437d6/aten/src/ATen/native/cuda/ActivationGeluKernel.cu#L36-L38 @@ -150,7 +179,8 @@ __device__ __forceinline__ T gelu_kernel(const T& x) { } template -__device__ __forceinline__ packed_t packed_gelu_kernel(const packed_t& val) { +__device__ __forceinline__ packed_t packed_gelu_kernel(const packed_t& val, + const float /*alpha*/) { // Equivalent to PyTorch GELU with 'none' approximation. // Refer to: // https://github.com/pytorch/pytorch/blob/8ac9b20d4b090c213799e81acf48a55ea8d437d6/aten/src/ATen/native/cuda/ActivationGeluKernel.cu#L36-L38 @@ -162,7 +192,8 @@ __device__ __forceinline__ packed_t packed_gelu_kernel(const packed_t& val) { } template -__device__ __forceinline__ T gelu_tanh_kernel(const T& x) { +__device__ __forceinline__ T gelu_tanh_kernel(const T& x, + const float /*alpha*/) { // Equivalent to PyTorch GELU with 'tanh' approximation. // Refer to: // https://github.com/pytorch/pytorch/blob/8ac9b20d4b090c213799e81acf48a55ea8d437d6/aten/src/ATen/native/cuda/ActivationGeluKernel.cu#L25-L30 @@ -176,7 +207,7 @@ __device__ __forceinline__ T gelu_tanh_kernel(const T& x) { template __device__ __forceinline__ packed_t -packed_gelu_tanh_kernel(const packed_t& val) { +packed_gelu_tanh_kernel(const packed_t& val, const float /*alpha*/) { // Equivalent to PyTorch GELU with 'tanh' approximation. // Refer to: // https://github.com/pytorch/pytorch/blob/8ac9b20d4b090c213799e81acf48a55ea8d437d6/aten/src/ATen/native/cuda/ActivationGeluKernel.cu#L25-L30 @@ -202,7 +233,7 @@ packed_gelu_tanh_kernel(const packed_t& val) { // clamped (max only) and up input is clamped (both sides) before the // activation function is applied. #define LAUNCH_ACTIVATION_GATE_KERNEL(KERNEL, PACKED_KERNEL, ACT_FIRST, \ - HAS_CLAMP, LIMIT) \ + HAS_CLAMP, LIMIT, ALPHA, BETA) \ auto dtype = input.scalar_type(); \ int d = input.size(-1) / 2; \ int64_t num_tokens = input.numel() / input.size(-1); \ @@ -230,7 +261,7 @@ packed_gelu_tanh_kernel(const packed_t& val) { PACKED_KERNEL::Type>, \ ACT_FIRST, true, HAS_CLAMP, true><<>>( \ out.mutable_data_ptr(), \ - input.const_data_ptr(), d, LIMIT); \ + input.const_data_ptr(), d, LIMIT, ALPHA, BETA); \ }); \ } else { \ VLLM_STABLE_DISPATCH_FLOATING_TYPES(dtype, "act_and_mul_kernel", [&] { \ @@ -240,7 +271,7 @@ packed_gelu_tanh_kernel(const packed_t& val) { PACKED_KERNEL::Type>, \ ACT_FIRST, true, HAS_CLAMP, false><<>>( \ out.mutable_data_ptr(), \ - input.const_data_ptr(), d, LIMIT); \ + input.const_data_ptr(), d, LIMIT, ALPHA, BETA); \ }); \ } \ } else { \ @@ -252,7 +283,7 @@ packed_gelu_tanh_kernel(const packed_t& val) { PACKED_KERNEL::Type>, \ ACT_FIRST, false, HAS_CLAMP><<>>( \ out.mutable_data_ptr(), input.const_data_ptr(), \ - d, LIMIT); \ + d, LIMIT, ALPHA, BETA); \ }); \ } @@ -260,14 +291,18 @@ void silu_and_mul(torch::stable::Tensor& out, // [..., d] torch::stable::Tensor& input) // [..., 2 * d] { LAUNCH_ACTIVATION_GATE_KERNEL(vllm::silu_kernel, vllm::packed_silu_kernel, - true, false, 0.0f); + true, false, 0.0f, 1.0f, 0.0f); } void silu_and_mul_clamp(torch::stable::Tensor& out, // [..., d] torch::stable::Tensor& input, // [..., 2 * d] - double limit) { + double limit, double alpha, double beta) { + // out = (gate.clamp(max=limit) * sigmoid(alpha * gate.clamp(max=limit))) + // * (up.clamp(+-limit) + beta) + // alpha=1.0, beta=0.0 reduce this to silu(gate) * up. LAUNCH_ACTIVATION_GATE_KERNEL(vllm::silu_kernel, vllm::packed_silu_kernel, - true, true, (float)limit); + true, true, (float)limit, (float)alpha, + (float)beta); } void mul_and_silu(torch::stable::Tensor& out, // [..., d] @@ -276,21 +311,22 @@ void mul_and_silu(torch::stable::Tensor& out, // [..., d] // The difference between mul_and_silu and silu_and_mul is that mul_and_silu // applies the silu to the latter half of the input. LAUNCH_ACTIVATION_GATE_KERNEL(vllm::silu_kernel, vllm::packed_silu_kernel, - false, false, 0.0f); + false, false, 0.0f, 1.0f, 0.0f); } void gelu_and_mul(torch::stable::Tensor& out, // [..., d] torch::stable::Tensor& input) // [..., 2 * d] { LAUNCH_ACTIVATION_GATE_KERNEL(vllm::gelu_kernel, vllm::packed_gelu_kernel, - true, false, 0.0f); + true, false, 0.0f, 1.0f, 0.0f); } void gelu_tanh_and_mul(torch::stable::Tensor& out, // [..., d] torch::stable::Tensor& input) // [..., 2 * d] { - LAUNCH_ACTIVATION_GATE_KERNEL( - vllm::gelu_tanh_kernel, vllm::packed_gelu_tanh_kernel, true, false, 0.0f); + LAUNCH_ACTIVATION_GATE_KERNEL(vllm::gelu_tanh_kernel, + vllm::packed_gelu_tanh_kernel, true, false, + 0.0f, 1.0f, 0.0f); } namespace vllm { diff --git a/csrc/libtorch_stable/cuda_vec_utils.cuh b/csrc/libtorch_stable/cuda_vec_utils.cuh index efbb09994d25..ec6e60724e65 100644 --- a/csrc/libtorch_stable/cuda_vec_utils.cuh +++ b/csrc/libtorch_stable/cuda_vec_utils.cuh @@ -21,7 +21,7 @@ // together enable 256-bit (v8.u32) PTX load/store instructions. // Use for PTX instruction selection with architecture fallback paths. #if !defined(USE_ROCM) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000 && \ - defined(CUDA_VERSION) && CUDA_VERSION >= 12090 + defined(CUDART_VERSION) && CUDART_VERSION >= 12090 #define VLLM_256B_PTX_ENABLED 1 #else #define VLLM_256B_PTX_ENABLED 0 diff --git a/csrc/libtorch_stable/fp32_router_gemm.cu b/csrc/libtorch_stable/fp32_router_gemm.cu index 04397e0893c2..80374d66a025 100644 --- a/csrc/libtorch_stable/fp32_router_gemm.cu +++ b/csrc/libtorch_stable/fp32_router_gemm.cu @@ -175,49 +175,52 @@ void invokeFp32RouterGemm(float* output, InputT const* mat_a, } // --------------------------------------------------------------------------- -// Explicit instantiations: M=1..32, E=256, H=3072, for both input types +// Explicit instantiations: M=1..32, for both input types, for the supported +// (E, H) pairs: (256, 3072) [MiniMax-M2/M2.5] and (128, 6144) [MiniMax-M3]. // --------------------------------------------------------------------------- -#define INSTANTIATE(T, M) \ - template void invokeFp32RouterGemm( \ - float*, T const*, float const*, cudaStream_t); - -#define INSTANTIATE_ALL(T) \ - INSTANTIATE(T, 1) \ - INSTANTIATE(T, 2) \ - INSTANTIATE(T, 3) \ - INSTANTIATE(T, 4) \ - INSTANTIATE(T, 5) \ - INSTANTIATE(T, 6) \ - INSTANTIATE(T, 7) \ - INSTANTIATE(T, 8) \ - INSTANTIATE(T, 9) \ - INSTANTIATE(T, 10) \ - INSTANTIATE(T, 11) \ - INSTANTIATE(T, 12) \ - INSTANTIATE(T, 13) \ - INSTANTIATE(T, 14) \ - INSTANTIATE(T, 15) \ - INSTANTIATE(T, 16) \ - INSTANTIATE(T, 17) \ - INSTANTIATE(T, 18) \ - INSTANTIATE(T, 19) \ - INSTANTIATE(T, 20) \ - INSTANTIATE(T, 21) \ - INSTANTIATE(T, 22) \ - INSTANTIATE(T, 23) \ - INSTANTIATE(T, 24) \ - INSTANTIATE(T, 25) \ - INSTANTIATE(T, 26) \ - INSTANTIATE(T, 27) \ - INSTANTIATE(T, 28) \ - INSTANTIATE(T, 29) \ - INSTANTIATE(T, 30) \ - INSTANTIATE(T, 31) \ - INSTANTIATE(T, 32) - -INSTANTIATE_ALL(float) -INSTANTIATE_ALL(__nv_bfloat16) +#define INSTANTIATE(T, M, E, H) \ + template void invokeFp32RouterGemm(float*, T const*, \ + float const*, cudaStream_t); + +#define INSTANTIATE_ALL(T, E, H) \ + INSTANTIATE(T, 1, E, H) \ + INSTANTIATE(T, 2, E, H) \ + INSTANTIATE(T, 3, E, H) \ + INSTANTIATE(T, 4, E, H) \ + INSTANTIATE(T, 5, E, H) \ + INSTANTIATE(T, 6, E, H) \ + INSTANTIATE(T, 7, E, H) \ + INSTANTIATE(T, 8, E, H) \ + INSTANTIATE(T, 9, E, H) \ + INSTANTIATE(T, 10, E, H) \ + INSTANTIATE(T, 11, E, H) \ + INSTANTIATE(T, 12, E, H) \ + INSTANTIATE(T, 13, E, H) \ + INSTANTIATE(T, 14, E, H) \ + INSTANTIATE(T, 15, E, H) \ + INSTANTIATE(T, 16, E, H) \ + INSTANTIATE(T, 17, E, H) \ + INSTANTIATE(T, 18, E, H) \ + INSTANTIATE(T, 19, E, H) \ + INSTANTIATE(T, 20, E, H) \ + INSTANTIATE(T, 21, E, H) \ + INSTANTIATE(T, 22, E, H) \ + INSTANTIATE(T, 23, E, H) \ + INSTANTIATE(T, 24, E, H) \ + INSTANTIATE(T, 25, E, H) \ + INSTANTIATE(T, 26, E, H) \ + INSTANTIATE(T, 27, E, H) \ + INSTANTIATE(T, 28, E, H) \ + INSTANTIATE(T, 29, E, H) \ + INSTANTIATE(T, 30, E, H) \ + INSTANTIATE(T, 31, E, H) \ + INSTANTIATE(T, 32, E, H) + +INSTANTIATE_ALL(float, 256, 3072) +INSTANTIATE_ALL(__nv_bfloat16, 256, 3072) +INSTANTIATE_ALL(float, 128, 6144) +INSTANTIATE_ALL(__nv_bfloat16, 128, 6144) #undef INSTANTIATE_ALL #undef INSTANTIATE diff --git a/csrc/libtorch_stable/fp32_router_gemm_entry.cu b/csrc/libtorch_stable/fp32_router_gemm_entry.cu index 4baa740de930..b4bc0a11d200 100644 --- a/csrc/libtorch_stable/fp32_router_gemm_entry.cu +++ b/csrc/libtorch_stable/fp32_router_gemm_entry.cu @@ -22,36 +22,42 @@ inline int getSMVersion() { } // namespace -static constexpr int FP32_NUM_EXPERTS = 256; -static constexpr int FP32_HIDDEN_DIM = 3072; static constexpr int FP32_MAX_TOKENS = 32; +// Supported (hidden_dim, num_experts) pairs (must match the instantiations in +// fp32_router_gemm.cu): (3072, 256) for MiniMax-M2/M2.5, (6144, 128) for M3. +static inline bool fp32_router_gemm_supported(int hidden_dim, int num_experts) { + return (hidden_dim == 3072 && num_experts == 256) || + (hidden_dim == 6144 && num_experts == 128); +} + // Forward declarations — 4 template params must match fp32_router_gemm.cu template void invokeFp32RouterGemm(float* output, InputT const* mat_a, float const* mat_b, cudaStream_t stream); -// LoopUnroller templated on InputT -template +// LoopUnroller templated on InputT, kNumExperts and kHiddenDim +template struct Fp32LoopUnroller { static void unroll(int num_tokens, float* output, InputT const* mat_a, float const* mat_b, cudaStream_t stream) { if (num_tokens == kBegin) { - invokeFp32RouterGemm( + invokeFp32RouterGemm( output, mat_a, mat_b, stream); } else { - Fp32LoopUnroller::unroll(num_tokens, output, - mat_a, mat_b, stream); + Fp32LoopUnroller::unroll(num_tokens, output, mat_a, mat_b, stream); } } }; -template -struct Fp32LoopUnroller { +template +struct Fp32LoopUnroller { static void unroll(int num_tokens, float* output, InputT const* mat_a, float const* mat_b, cudaStream_t stream) { if (num_tokens == kEnd) { - invokeFp32RouterGemm( + invokeFp32RouterGemm( output, mat_a, mat_b, stream); } else { throw std::invalid_argument( @@ -60,6 +66,23 @@ struct Fp32LoopUnroller { } }; +// Dispatch over the supported (num_experts, hidden_dim) pairs. +template +void dispatchFp32RouterGemm(int num_experts, int hidden_dim, int num_tokens, + float* output, InputT const* mat_a, + float const* mat_b, cudaStream_t stream) { + if (num_experts == 256 && hidden_dim == 3072) { + Fp32LoopUnroller::unroll( + num_tokens, output, mat_a, mat_b, stream); + } else if (num_experts == 128 && hidden_dim == 6144) { + Fp32LoopUnroller::unroll( + num_tokens, output, mat_a, mat_b, stream); + } else { + throw std::invalid_argument( + "fp32_router_gemm: unsupported (hidden_dim, num_experts) pair"); + } +} + void fp32_router_gemm( torch::stable::Tensor& output, // [num_tokens, num_experts] torch::stable::Tensor const& mat_a, // [num_tokens, hidden_dim] @@ -85,10 +108,10 @@ void fp32_router_gemm( STD_TORCH_CHECK( mat_a.size(1) == mat_b.size(1), "fp32_router_gemm: mat_a and mat_b must have the same hidden_dim"); - STD_TORCH_CHECK(hidden_dim == FP32_HIDDEN_DIM, - "fp32_router_gemm: expected hidden_dim=3072"); - STD_TORCH_CHECK(num_experts == FP32_NUM_EXPERTS, - "fp32_router_gemm: expected num_experts=256"); + STD_TORCH_CHECK( + fp32_router_gemm_supported(hidden_dim, num_experts), + "fp32_router_gemm: supported (hidden_dim, num_experts) pairs are " + "(3072, 256) and (6144, 128)"); STD_TORCH_CHECK(num_tokens <= FP32_MAX_TOKENS, "fp32_router_gemm: num_tokens must be in [0, 32]"); STD_TORCH_CHECK( @@ -113,12 +136,13 @@ void fp32_router_gemm( if (mat_a.scalar_type() == torch::headeronly::ScalarType::BFloat16) { auto const* mat_a_ptr = reinterpret_cast<__nv_bfloat16 const*>(mat_a.data_ptr()); - Fp32LoopUnroller<__nv_bfloat16, 1, FP32_MAX_TOKENS>::unroll( - num_tokens, out_ptr, mat_a_ptr, mat_b_ptr, stream); + dispatchFp32RouterGemm<__nv_bfloat16>(num_experts, hidden_dim, num_tokens, + out_ptr, mat_a_ptr, mat_b_ptr, + stream); } else { auto const* mat_a_ptr = reinterpret_cast(mat_a.data_ptr()); - Fp32LoopUnroller::unroll( - num_tokens, out_ptr, mat_a_ptr, mat_b_ptr, stream); + dispatchFp32RouterGemm(num_experts, hidden_dim, num_tokens, out_ptr, + mat_a_ptr, mat_b_ptr, stream); } } diff --git a/csrc/libtorch_stable/fused_minimax_m3_qknorm_rope_kv_insert_kernel.cu b/csrc/libtorch_stable/fused_minimax_m3_qknorm_rope_kv_insert_kernel.cu new file mode 100644 index 000000000000..06c8048cd900 --- /dev/null +++ b/csrc/libtorch_stable/fused_minimax_m3_qknorm_rope_kv_insert_kernel.cu @@ -0,0 +1,675 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * SPDX-FileCopyrightText: Copyright contributors to the vLLM project + * + * Horizontally-fused MiniMax-M3 attention pre-processing kernel. + * + * Replaces the per-token Python sequence in + * ``MiniMaxM3SparseAttention.forward`` / ``MiniMaxM3Attention.forward``: + * + * q = q_norm(q); k = k_norm(k); q, k = rotary_emb(pos, q, k) + * index_q = index_q_norm(index_q); index_k = index_k_norm(index_k) + * index_q, index_k = rotary_emb(pos, index_q, index_k) + * _insert_kv(k, v, index_k) + * + * All branches share head_dim=128 and the *same* partial-NeoX RoPE table + * (``rotary_dim`` rotated, the trailing dims pass through). The four norms + * are Gemma-style RMSNorm (``x * rsqrt(mean(x^2)+eps) * (1 + weight)``) with + * independent weights. + * + * Everything lives in a single fused ``qkv`` tensor. The sparse layer's + * fused projection (MinimaxM3QKVParallelLinearWithIndexer) emits, per token:: + * + * [ q | k | v | index_q | index_k ] (the "5 results") + * + * while the dense layer emits just ``[ q | k | v ]``. The kernel reads the + * index branch straight out of that packed row -- no separate index tensors. + * + * One kernel, one grid; each warp owns one (token, head-slot) pair. Slot + * enumeration per token: + * [0, nq) Q heads -> norm(q_w) + RoPE, write + * qkv [nq, nq+nkv) K heads -> norm(k_w) + RoPE, write + * qkv + * (+ insert into key cache) + * [nq+nkv, nq+2*nkv) V heads -> insert into value cache + * IQ heads (niq) -> norm(iq_w) + RoPE, write iq + * IK (1) -> norm(ik_w) + RoPE + * (+ insert into index cache) + * + * The IQ/IK warps address the index_q/index_k sub-blocks *inside* qkv at the + * fixed physical offsets (nq+2*nkv)*128 and (nq+2*nkv+niq)*128. + * + * Dense vs sparse is a compile-time choice via the ``kIsSparse``/``kInsertKV`` + * template bools (3 instantiations: dense , sparse-profiling + * , sparse-serving ), so the index slots, the V slots + * and the cache inserts fold away entirely on paths that don't use them. The + * dense layer passes no caches/index: norm+RoPE happens in place and the + * generic ``Attention`` layer owns the cache write. + * + * Q/K and (sparse) index_q/index_k are all rewritten in place inside the fused + * ``qkv`` tensor. Caches (bf16) are scatter-written by slot. + */ + +#include +#include +#include + +#include "torch_utils.h" + +#include "../cuda_compat.h" +#include "../type_convert.cuh" +#include "../attention/dtype_fp8.cuh" +#include "dispatch_utils.h" + +#ifdef USE_ROCM + #include "../quantization/w8a8/fp8/amd/quant_utils.cuh" +#else + #include "../quantization/w8a8/fp8/nvidia/quant_utils.cuh" +#endif + +#ifndef FINAL_MASK + #ifdef USE_ROCM + #define FINAL_MASK 0xffffffffffffffffULL + #else + #define FINAL_MASK 0xffffffffu + #endif +#endif + +namespace vllm { +namespace minimax_m3_fused_ops { + +namespace { +inline int getSMVersion() { + auto* props = get_device_prop(); + return props->major * 10 + props->minor; +} +} // namespace + +// ──────────────────────────────────────────────────────────────────────────── +// Constants (hard-coded for MiniMax-M3-preview). +// ──────────────────────────────────────────────────────────────────────────── +constexpr int kHeadDim = 128; +constexpr int kNumLanes = 32; +constexpr int kElemsPerLane = kHeadDim / kNumLanes; // 4 + +// ──────────────────────────────────────────────────────────────────────────── +// Helpers +// ──────────────────────────────────────────────────────────────────────────── +__device__ __forceinline__ float warpReduceSum(float val) { +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) { + val += __shfl_xor_sync(FINAL_MASK, val, mask, 32); + } + return val; +} + +// Gemma RMSNorm over the full head (no-op when ``weight == nullptr``), rounded +// back to scalar_t like the materialized unfused norm output, followed by +// partial NeoX RoPE on the leading ``rotary_dim`` dims. Each lane owns +// ``kElemsPerLane`` contiguous dims [laneId*4, laneId*4+4). +template +__device__ __forceinline__ void normAndRope( + float (&elems)[kElemsPerLane], int const laneId, float const eps, + scalar_t const* __restrict__ weight, // [kHeadDim] or nullptr (no norm) + bool const do_rope, int const rotary_dim, + scalar_t const* __restrict__ cos_ptr, // cos_sin_cache + pos*rotary_dim + bool const apply_norm) { + // ── Gemma RMSNorm: x * rsqrt(mean(x^2)+eps) * (1 + w) ────────────────── + if (apply_norm) { + float sumsq = 0.0f; +#pragma unroll + for (int i = 0; i < kElemsPerLane; i++) sumsq += elems[i] * elems[i]; + sumsq = warpReduceSum(sumsq); + float const rms_rcp = rsqrtf(sumsq / static_cast(kHeadDim) + eps); +#pragma unroll + for (int i = 0; i < kElemsPerLane; i++) { + int const dim = laneId * kElemsPerLane + i; + float const w = 1.0f + static_cast(weight[dim]); + elems[i] = elems[i] * rms_rcp * w; + } + } + + // ── Partial NeoX RoPE on dims [0, rotary_dim) ────────────────────────── + // half = rotary_dim/2. Pair (i, i+half) for i in [0, half). Lane L owns + // dims [4L, 4L+4); since half is a multiple of 4, a lane lies wholly in the + // first half (own=x[i]) or second half (own=x[i+half]); its partner lives + // ``half/4`` lanes away (XOR with that distance). + if (do_rope) { + int const half = rotary_dim / 2; + int const dim0 = laneId * kElemsPerLane; + bool const in_rope = dim0 < rotary_dim; + int const lane_xor = half / kElemsPerLane; // partner-lane distance + + float partner[kElemsPerLane]; +#pragma unroll + for (int i = 0; i < kElemsPerLane; i++) { + partner[i] = __shfl_xor_sync(FINAL_MASK, elems[i], lane_xor, 32); + } + if (in_rope) { + bool const first_half = dim0 < half; + int const i_base = first_half ? dim0 : (dim0 - half); // cos/sin index + scalar_t const* sin_ptr = cos_ptr + half; +#pragma unroll + for (int i = 0; i < kElemsPerLane; i++) { + float const c = static_cast(cos_ptr[i_base + i]); + float const s = static_cast(sin_ptr[i_base + i]); + if (first_half) { + elems[i] = elems[i] * c - partner[i] * s; + } else { + elems[i] = elems[i] * c + partner[i] * s; + } + } + } + } +} + +// Load 4 contiguous bf16 -> 4 fp32 registers. +template +__device__ __forceinline__ void loadElems(scalar_t const* __restrict__ src, + float (&elems)[kElemsPerLane]) { + using Converter = vllm::_typeConvert; + uint2 v = *reinterpret_cast(src); + auto const* p = + reinterpret_cast(&v); +#pragma unroll + for (int i = 0; i < kElemsPerLane / 2; i++) { + float2 f2 = Converter::convert(p[i]); + elems[2 * i] = f2.x; + elems[2 * i + 1] = f2.y; + } +} + +// Store 4 fp32 registers -> 4 contiguous bf16. +template +__device__ __forceinline__ void storeElems( + scalar_t* __restrict__ dst, float const (&elems)[kElemsPerLane]) { + using Converter = vllm::_typeConvert; + uint2 v; + auto* p = reinterpret_cast(&v); +#pragma unroll + for (int i = 0; i < kElemsPerLane / 2; i++) { + p[i] = Converter::convert(make_float2(elems[2 * i], elems[2 * i + 1])); + } + *reinterpret_cast(dst) = v; +} + +template +__device__ __forceinline__ void storeCacheElems( + cache_t* __restrict__ dst, float const (&elems)[kElemsPerLane]) { + if constexpr (kv_dt == Fp8KVCacheDataType::kAuto) { + // kAuto means unquantized KV cache here: cache_t == scalar_t, so store the + // model dtype directly. FP8 cache dtypes use the conversion path below. + storeElems(reinterpret_cast(dst), elems); + } else { +#pragma unroll + for (int i = 0; i < kElemsPerLane; i++) { + dst[i] = fp8::scaled_convert(elems[i], 1.0f); + } + } +} + +// ──────────────────────────────────────────────────────────────────────────── +// Kernel +// ──────────────────────────────────────────────────────────────────────────── +// Grid: 1D, ceil(num_tokens * slots_per_token / warps_per_block). +// Each warp = one (token, slot). +// +// `kIsSparse` and `kInsertKV` are compile-time template bools, so all the +// branch decisions that distinguish the dense layer from the sparse layer +// (index slots, KV/index inserts, V slots) fold away per instantiation. +// Three instantiations are built: dense , sparse-profiling +// and sparse-serving . Slots per token: +// Q : nq (always — norm+RoPE) +// K : nkv (always — norm+RoPE; +K-cache insert) +// V : nkv only if kInsertKV (V-cache insert; no warps in dense) +// IQ: niq only if kIsSparse (norm+RoPE) +// IK: 1 only if kIsSparse (norm+RoPE; +index-cache insert) +template +__global__ void fusedMiniMaxM3QNormRopeKVInsertKernel( + scalar_t* __restrict__ qkv, // [N, qkv_row] in/out (packs index if sparse) + scalar_t* __restrict__ q_out, // [N, nq*128] contiguous, or nullptr + scalar_t* __restrict__ index_q_out, // [N, niq*128] contiguous, or nullptr + scalar_t const* __restrict__ q_norm_w, + scalar_t const* __restrict__ k_norm_w, + scalar_t const* __restrict__ iq_norm_w, + scalar_t const* __restrict__ ik_norm_w, + scalar_t const* __restrict__ cos_sin_cache, // [max_pos, rotary_dim] + int64_t const* __restrict__ positions, // [N] i64 + int64_t const* __restrict__ slot_mapping, // main K/V slots or nullptr + int64_t const* __restrict__ index_slot_mapping, // index K slots/nullptr + cache_t* __restrict__ kv_cache, // [nb,2,bs,nkv,128] or nullptr + scalar_t* __restrict__ index_cache, // [nb*bs, 128] or nullptr + float const eps, int const rotary_dim, int const num_tokens, int const nq, + int const nkv, int const niq, int const block_size, + // kv_cache strides (in elements) for logical shape [nb, 2, bs, nkv, 128]. + // The head_dim (last) dim is always innermost-contiguous (stride 1), so the + // NHD/HND layout choice is fully captured by these four strides: NHD keeps + // s_token < s_head, HND swaps them. dim_base addresses head_dim directly. + int64_t const kv_s_block, int64_t const kv_s_kv, int64_t const kv_s_token, + int64_t const kv_s_head) { +#if (!defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 800) && !defined(USE_ROCM) + // _typeConvert is unavailable on pre-Ampere; the M3 kernel only + // runs with bf16/fp16 inputs in practice. Discard the bf16 body there. + if constexpr (std::is_same_v) { + return; + } else { +#endif + int const warpsPerBlock = blockDim.x / 32; + int const laneId = threadIdx.x % 32; + int const globalWarpIdx = blockIdx.x * warpsPerBlock + (threadIdx.x / 32); + + // Slot layout (compile-time gated: dense has neither V nor index slots). + int const v_slots = kInsertKV ? nkv : 0; + int const idx_slots = kIsSparse ? niq + 1 : 0; + int const slots_per_token = nq + nkv + v_slots + idx_slots; + + int const tokenIdx = globalWarpIdx / slots_per_token; + int const slot = globalWarpIdx % slots_per_token; + if (tokenIdx >= num_tokens) return; + + // Slot boundaries. + int const k_begin = nq; + int const v_begin = nq + nkv; // valid only when kInsertKV + int const iq_begin = nq + nkv + v_slots; // index block start + int const ik_slot = iq_begin + niq; // valid only when kIsSparse + + bool const isQ = slot < k_begin; + bool const isK = slot >= k_begin && slot < v_begin; + bool isV = false; + if constexpr (kInsertKV) isV = slot >= v_begin && slot < v_begin + nkv; + bool isIQ = false, isIK = false; + if constexpr (kIsSparse) { + isIQ = slot >= iq_begin && slot < ik_slot; + isIK = slot == ik_slot; + } + + int const dim_base = laneId * kElemsPerLane; + // Physical row width of qkv: the dense layer packs [q|k|v]; the sparse + // layer additionally packs [index_q (niq heads) | index_k (1 head)]. + int const qkv_row = (nq + 2 * nkv + (kIsSparse ? (niq + 1) : 0)) * kHeadDim; + + // ── Resolve source pointer + per-branch parameters. ──────────────────── + scalar_t* row_ptr = nullptr; // in-place output location + scalar_t const* norm_w = nullptr; // nullptr -> skip norm (V) + bool do_rope = true; + int head = 0; // kv head index for inserts + + if (isQ) { + row_ptr = + qkv + static_cast(tokenIdx) * qkv_row + slot * kHeadDim; + norm_w = q_norm_w; + } else if (isK) { + head = slot - k_begin; + row_ptr = + qkv + static_cast(tokenIdx) * qkv_row + slot * kHeadDim; + norm_w = k_norm_w; + } else if (isV) { + // qkv V section starts at slot index (nq + nkv): slot * kHeadDim is the + // correct in-tensor offset. + head = slot - v_begin; + row_ptr = + qkv + static_cast(tokenIdx) * qkv_row + slot * kHeadDim; + norm_w = nullptr; // V: no norm, no rope + do_rope = false; + } else if (isIQ) { + // index_q sub-block lives at physical offset (nq+2*nkv)*128 in qkv. + int const ih = slot - iq_begin; + row_ptr = qkv + static_cast(tokenIdx) * qkv_row + + (nq + 2 * nkv + ih) * kHeadDim; + norm_w = iq_norm_w; + } else { // isIK -- single shared index key at (nq+2*nkv+niq)*128. + row_ptr = qkv + static_cast(tokenIdx) * qkv_row + + (nq + 2 * nkv + niq) * kHeadDim; + norm_w = ik_norm_w; + } + + // Store destination. Q and index_q are gathered into dedicated contiguous + // output buffers (when provided) so the downstream SM100 sparse kernel's + // flat TMA descriptor can address them as [tokens*heads, head_dim]; this + // folds the de-interleaving into the store the kernel already does, instead + // of a separate q.contiguous() copy. Everything else stays in place. + scalar_t* store_ptr = row_ptr; + if (isQ && q_out != nullptr) { + store_ptr = q_out + static_cast(tokenIdx) * nq * kHeadDim + + slot * kHeadDim; + } else if (isIQ && index_q_out != nullptr) { + store_ptr = index_q_out + + static_cast(tokenIdx) * niq * kHeadDim + + (slot - iq_begin) * kHeadDim; + } + + // PDL: wait for the predecessor kernel (the qkv-projection GEMM that + // produces ``qkv``) to finish before touching any global memory. No-op + // when PDL is not enabled on the launch. The CUDA runtime wrapper emits + // the griddepcontrol.wait PTX with the required memory clobber internally. +#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) + cudaGridDependencySynchronize(); +#endif + + // ── Load -> norm+rope (fp32) -> store back in place. ─────────────────── + float elems[kElemsPerLane]; + loadElems(row_ptr + dim_base, elems); + + if (!isV) { + int64_t const pos = positions[tokenIdx]; + scalar_t const* cos_ptr = cos_sin_cache + pos * rotary_dim; + normAndRope(elems, laneId, eps, norm_w, do_rope, rotary_dim, + cos_ptr, /*apply_norm=*/norm_w != nullptr); + storeElems(store_ptr + dim_base, elems); + } + + // ── Cache inserts (sparse serving only). ─────────────────────────────── + if constexpr (kInsertKV) { + // Guard (not early-return) so every thread reaches the PDL trigger below. + int64_t const sm = (isK || isV) + ? slot_mapping[tokenIdx] + : (isIK ? index_slot_mapping[tokenIdx] : -1); + if (sm >= 0) { // skip padded / unscheduled tokens + if (isIK) { + scalar_t* dst = index_cache + sm * kHeadDim + dim_base; + storeElems(dst, elems); + } else if (isK || isV) { + // kv_cache logical shape [num_blocks, 2, block_size, nkv, head_dim]. + // Paging is logical (block = sm/block_size, token = sm%block_size); + // the physical NHD/HND layout is honoured via the passed strides. + int64_t const b = sm / block_size; + int64_t const t = sm % block_size; + int const kv = isK ? 0 : 1; + int64_t const off = + b * kv_s_block + kv * kv_s_kv + t * kv_s_token + head * kv_s_head; + storeCacheElems(kv_cache + off + dim_base, + elems); + } + } + } + + // PDL: signal that this kernel is done so a dependent successor may launch + // early. No-op when PDL is not enabled on the launch. +#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) + cudaTriggerProgrammaticLaunchCompletion(); +#endif +#if (!defined(__CUDA_ARCH__) || __CUDA_ARCH__ < 800) && !defined(USE_ROCM) + } +#endif +} + +// ──────────────────────────────────────────────────────────────────────────── +// Launch wrapper +// ──────────────────────────────────────────────────────────────────────────── +template +void launchFusedMiniMaxM3(scalar_t* qkv, scalar_t* q_out, scalar_t* index_q_out, + scalar_t const* q_norm_w, scalar_t const* k_norm_w, + scalar_t const* iq_norm_w, scalar_t const* ik_norm_w, + scalar_t const* cos_sin_cache, + int64_t const* positions, int64_t const* slot_mapping, + int64_t const* index_slot_mapping, cache_t* kv_cache, + scalar_t* index_cache, float const eps, + int const rotary_dim, int const num_tokens, + int const nq, int const nkv, int const niq, + int const block_size, int64_t const kv_s_block, + int64_t const kv_s_kv, int64_t const kv_s_token, + int64_t const kv_s_head, bool const has_index, + bool const insert_kv, cudaStream_t stream) { + // Slot count must match the kernel's compile-time gating. + int const v_slots = insert_kv ? nkv : 0; + int const idx_slots = has_index ? niq + 1 : 0; + int const slots_per_token = nq + nkv + v_slots + idx_slots; + + constexpr int kBlockSize = 256; + constexpr int kWarpsPerBlock = kBlockSize / 32; + int64_t const total_warps = + static_cast(num_tokens) * slots_per_token; + int const grid = + static_cast((total_warps + kWarpsPerBlock - 1) / kWarpsPerBlock); + if (grid == 0) return; + +#ifndef USE_ROCM + // PDL: enable programmatic stream serialization whenever the hardware + // supports it (SM90+). On pre-Hopper GPUs the attribute is unavailable, so + // leave numAttrs = 0 and launch as a regular kernel via cudaLaunchKernelEx. + static int const sm_version = getSMVersion(); + cudaLaunchConfig_t config; + config.gridDim = dim3(grid); + config.blockDim = dim3(kBlockSize); + config.dynamicSmemBytes = 0; + config.stream = stream; + cudaLaunchAttribute attrs[1]; + attrs[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; + attrs[0].val.programmaticStreamSerializationAllowed = 1; + config.attrs = attrs; + config.numAttrs = (sm_version >= 90) ? 1 : 0; + + #define LAUNCH(IS_SPARSE, INSERT) \ + cudaLaunchKernelEx( \ + &config, \ + fusedMiniMaxM3QNormRopeKVInsertKernel, \ + qkv, q_out, index_q_out, q_norm_w, k_norm_w, iq_norm_w, ik_norm_w, \ + cos_sin_cache, positions, slot_mapping, index_slot_mapping, kv_cache, \ + index_cache, eps, rotary_dim, num_tokens, nq, nkv, niq, block_size, \ + kv_s_block, kv_s_kv, kv_s_token, kv_s_head) +#else + // ROCm: standard kernel launch syntax (no PDL/stream serialization). + // clang-format off + #define LAUNCH(IS_SPARSE, INSERT) \ + fusedMiniMaxM3QNormRopeKVInsertKernel \ + <<>>( \ + qkv, q_out, index_q_out, q_norm_w, k_norm_w, iq_norm_w, \ + ik_norm_w, cos_sin_cache, positions, slot_mapping, \ + index_slot_mapping, kv_cache, index_cache, eps, rotary_dim, \ + num_tokens, nq, nkv, niq, block_size, kv_s_block, kv_s_kv, \ + kv_s_token, kv_s_head) + // clang-format on +#endif + + if (has_index) { + if (insert_kv) { + LAUNCH(true, true); // sparse serving + } else { + LAUNCH(true, false); // sparse profiling + } + } else { + // Dense layer: never has an index branch and never inserts here (the + // generic Attention layer owns the KV insert). + LAUNCH(false, false); + } +#undef LAUNCH +} + +} // namespace minimax_m3_fused_ops +} // namespace vllm + +#define CALL_FUSED_MINIMAX_M3(_RAW_T, CACHE_T, KV_DTYPE) \ + vllm::minimax_m3_fused_ops::launchFusedMiniMaxM3( \ + reinterpret_cast(qkv.data_ptr()), \ + q_out.has_value() ? reinterpret_cast(q_out->data_ptr()) : nullptr, \ + index_q_out.has_value() ? reinterpret_cast(index_q_out->data_ptr()) \ + : nullptr, \ + reinterpret_cast(q_norm_weight.data_ptr()), \ + reinterpret_cast(k_norm_weight.data_ptr()), \ + has_index ? reinterpret_cast(index_q_norm_weight->data_ptr()) \ + : nullptr, \ + has_index ? reinterpret_cast(index_k_norm_weight->data_ptr()) \ + : nullptr, \ + reinterpret_cast(cos_sin_cache.data_ptr()), \ + reinterpret_cast(positions.data_ptr()), \ + insert_kv ? reinterpret_cast(slot_mapping->data_ptr()) \ + : nullptr, \ + insert_kv ? reinterpret_cast( \ + effective_index_slot_mapping->data_ptr()) \ + : nullptr, \ + insert_kv ? reinterpret_cast(kv_cache->data_ptr()) : nullptr, \ + (insert_kv && has_index) \ + ? reinterpret_cast(index_cache->data_ptr()) \ + : nullptr, \ + static_cast(eps), static_cast(rotary_dim), num_tokens, nq, \ + nkv, niq, static_cast(block_size), kv_s_block, kv_s_kv, kv_s_token, \ + kv_s_head, has_index, insert_kv, stream) + +// ──────────────────────────────────────────────────────────────────────────── +// Torch op wrapper +// ──────────────────────────────────────────────────────────────────────────── +void fused_minimax_m3_qknorm_rope_kv_insert( + torch::stable::Tensor& qkv, // [N, qkv_row] (packs index if sparse) + torch::stable::Tensor const& q_norm_weight, // [128] + torch::stable::Tensor const& k_norm_weight, // [128] + torch::stable::Tensor const& cos_sin_cache, // [max_pos, rotary_dim] + torch::stable::Tensor const& positions, // [N] i64 + int64_t num_heads, int64_t num_kv_heads, int64_t rotary_dim, double eps, + std::optional index_q_norm_weight, // [128] + std::optional index_k_norm_weight, // [128] + int64_t num_index_heads, // niq; 0 => dense + std::optional slot_mapping, // [N] i64 + std::optional index_slot_mapping, // [N] i64 + std::optional kv_cache, // [nb,2,bs,nkv,128] + std::optional index_cache, // [nb,bs,128] + int64_t block_size, + std::optional q_out, // [N, nq*128] contiguous + std::optional + index_q_out, // [N, niq*128] contiguous + const std::string& kv_cache_dtype) { + STD_TORCH_CHECK(qkv.is_cuda() && qkv.is_contiguous(), + "qkv must be contiguous CUDA"); + STD_TORCH_CHECK( + qkv.scalar_type() == torch::headeronly::ScalarType::Half || + qkv.scalar_type() == torch::headeronly::ScalarType::BFloat16, + "qkv must be float16 or bfloat16"); + STD_TORCH_CHECK( + positions.is_cuda() && + positions.scalar_type() == torch::headeronly::ScalarType::Long, + "positions must be int64 CUDA"); + STD_TORCH_CHECK(cos_sin_cache.is_cuda() && cos_sin_cache.is_contiguous(), + "cos_sin_cache must be contiguous CUDA"); + STD_TORCH_CHECK(cos_sin_cache.scalar_type() == qkv.scalar_type(), + "cos_sin_cache dtype must match qkv"); + STD_TORCH_CHECK( + cos_sin_cache.dim() == 2 && cos_sin_cache.size(1) == rotary_dim, + "cos_sin_cache shape [max_pos, rotary_dim]"); + + STD_TORCH_CHECK(q_norm_weight.scalar_type() == qkv.scalar_type() && + k_norm_weight.scalar_type() == qkv.scalar_type(), + "q/k norm weight dtype must match qkv"); + STD_TORCH_CHECK( + q_norm_weight.numel() == vllm::minimax_m3_fused_ops::kHeadDim && + k_norm_weight.numel() == vllm::minimax_m3_fused_ops::kHeadDim, + "q/k norm weight must have 128 elements"); + STD_TORCH_CHECK(rotary_dim > 0 && rotary_dim % 8 == 0 && + rotary_dim <= vllm::minimax_m3_fused_ops::kHeadDim, + "rotary_dim must be a positive multiple of 8 and <= 128"); + + int const num_tokens = static_cast(qkv.size(0)); + int const nq = static_cast(num_heads); + int const nkv = static_cast(num_kv_heads); + int const niq = static_cast(num_index_heads); + + // The sparse layer packs the index branch ([index_q (niq heads) | index_k + // (1 head)]) right after [q|k|v] in the same row; the dense layer does not. + bool const has_index = niq > 0; + bool const insert_kv = kv_cache.has_value(); + vllm::Fp8KVCacheDataType const kv_dt = + vllm::get_fp8_kv_cache_data_type(kv_cache_dtype); + int const kHeadDim = vllm::minimax_m3_fused_ops::kHeadDim; + int const expected_row = + (nq + 2 * nkv + (has_index ? niq + 1 : 0)) * kHeadDim; + STD_TORCH_CHECK(qkv.size(1) == expected_row, + "qkv last dim must be (num_heads + 2*num_kv_heads" + " + num_index_heads + 1) * 128 for sparse, " + "(num_heads + 2*num_kv_heads) * 128 for dense"); + + // Only the sparse layer inserts here (dense lets the generic Attention layer + // own the KV write); there is no dense+insert kernel instantiation. + STD_TORCH_CHECK( + !insert_kv || has_index, + "insert mode (kv_cache) requires the index branch (sparse layer)"); + if (has_index) { + STD_TORCH_CHECK( + index_q_norm_weight.has_value() && index_k_norm_weight.has_value(), + "index branch requires both index norm weights"); + STD_TORCH_CHECK(index_q_norm_weight->scalar_type() == qkv.scalar_type() && + index_k_norm_weight->scalar_type() == qkv.scalar_type(), + "index norm weights dtype must match qkv"); + STD_TORCH_CHECK(index_q_norm_weight->numel() == kHeadDim && + index_k_norm_weight->numel() == kHeadDim, + "index norm weights must have 128 elements"); + } + // kv_cache strides (logical shape [nb, 2, bs, nkv, head_dim]). Read straight + // off the tensor so the kernel honours whatever physical layout the attention + // backend allocated (NHD: stride order (0,1,2,3,4); HND: (0,1,3,2,4)). No new + // op argument is needed -- the strides ride along with the tensor itself. + int64_t kv_s_block = 0, kv_s_kv = 0, kv_s_token = 0, kv_s_head = 0; + torch::stable::Tensor const* effective_index_slot_mapping = nullptr; + if (insert_kv) { + STD_TORCH_CHECK( + slot_mapping.has_value() && slot_mapping->is_cuda() && + slot_mapping->scalar_type() == torch::headeronly::ScalarType::Long, + "insert mode requires int64 CUDA slot_mapping"); + STD_TORCH_CHECK( + !index_slot_mapping.has_value() || + (index_slot_mapping->is_cuda() && + index_slot_mapping->scalar_type() == + torch::headeronly::ScalarType::Long && + index_slot_mapping->numel() == slot_mapping->numel()), + "index_slot_mapping must be int64 CUDA with slot_mapping length"); + if (kv_dt == vllm::Fp8KVCacheDataType::kAuto) { + STD_TORCH_CHECK(kv_cache->scalar_type() == qkv.scalar_type(), + "auto kv_cache dtype must match qkv"); + } else { + STD_TORCH_CHECK( + kv_cache->scalar_type() == torch::headeronly::ScalarType::Byte, + "fp8 kv_cache must use uint8 storage"); + } + STD_TORCH_CHECK(index_cache.has_value() && + index_cache->scalar_type() == qkv.scalar_type(), + "insert mode requires matching index_cache"); + STD_TORCH_CHECK(kv_cache->dim() == 5 && kv_cache->stride(4) == 1, + "kv_cache must be [nb,2,bs,nkv,head_dim] with contiguous " + "head_dim (stride(4)==1)"); + kv_s_block = kv_cache->stride(0); + kv_s_kv = kv_cache->stride(1); + kv_s_token = kv_cache->stride(2); + kv_s_head = kv_cache->stride(3); + effective_index_slot_mapping = index_slot_mapping.has_value() + ? &index_slot_mapping.value() + : &slot_mapping.value(); + } + // Optional contiguous gather targets: when given, the normed/roped q (and + // index_q) are written here instead of in place, so callers avoid a separate + // .contiguous() copy. index_q_out only makes sense on the sparse path. + if (q_out.has_value()) { + STD_TORCH_CHECK( + q_out->is_cuda() && q_out->is_contiguous() && + q_out->scalar_type() == qkv.scalar_type(), + "q_out must be a contiguous CUDA tensor matching qkv dtype"); + STD_TORCH_CHECK( + q_out->numel() == static_cast(num_tokens) * nq * kHeadDim, + "q_out must have num_tokens * num_heads * 128 elements"); + } + if (index_q_out.has_value()) { + STD_TORCH_CHECK( + has_index, + "index_q_out requires the index branch (num_index_heads > 0)"); + STD_TORCH_CHECK( + index_q_out->is_cuda() && index_q_out->is_contiguous() && + index_q_out->scalar_type() == qkv.scalar_type(), + "index_q_out must be a contiguous CUDA tensor matching qkv dtype"); + STD_TORCH_CHECK(index_q_out->numel() == + static_cast(num_tokens) * niq * kHeadDim, + "index_q_out must have num_tokens * num_index_heads * 128 " + "elements"); + } + + const torch::stable::accelerator::DeviceGuard device_guard( + qkv.get_device_index()); + auto stream = get_current_cuda_stream(qkv.get_device_index()); + + VLLM_STABLE_DISPATCH_HALF_TYPES( + qkv.scalar_type(), "fused_minimax_m3_qknorm_rope_kv_insert", [&] { + using st = scalar_t; + DISPATCH_BY_KV_CACHE_DTYPE(qkv.scalar_type(), kv_cache_dtype, + CALL_FUSED_MINIMAX_M3); + }); +} + +#undef CALL_FUSED_MINIMAX_M3 diff --git a/csrc/libtorch_stable/layernorm_kernels.cu b/csrc/libtorch_stable/layernorm_kernels.cu index 37df6be329fb..eb121b0b8807 100644 --- a/csrc/libtorch_stable/layernorm_kernels.cu +++ b/csrc/libtorch_stable/layernorm_kernels.cu @@ -11,7 +11,7 @@ namespace vllm { // TODO(woosuk): Further optimize this kernel. -template +template __global__ void rms_norm_kernel( scalar_t* __restrict__ out, // [..., hidden_size] const scalar_t* __restrict__ input, // [..., hidden_size] @@ -20,7 +20,7 @@ __global__ void rms_norm_kernel( const int64_t input_stride_d4, // input.stride(-4) const int64_t input_shape_d2, // input.size(-2) const int64_t input_shape_d3, // input.size(-3) - const scalar_t* __restrict__ weight, // [hidden_size] + const scalar_t* __restrict__ weight, // [hidden_size], null if !HasWeight const float epsilon, const int num_tokens, const int hidden_size) { __shared__ float s_variance; float variance = 0.0f; @@ -74,11 +74,19 @@ __global__ void rms_norm_kernel( for (int i = threadIdx.x; i < hidden_size / VEC_SIZE; i += blockDim.x) { vec_n_t dst; vec_n_t src1 = v_in[i]; - vec_n_t src2 = v_w[i]; + vec_n_t src2; + if constexpr (HasWeight) { + src2 = v_w[i]; + } #pragma unroll for (int j = 0; j < VEC_SIZE; j++) { float x = static_cast(src1.val[j]); - dst.val[j] = static_cast(x * s_variance) * src2.val[j]; + scalar_t normalized = static_cast(x * s_variance); + if constexpr (HasWeight) { + dst.val[j] = normalized * src2.val[j]; + } else { + dst.val[j] = normalized; + } } v_out[i] = dst; } @@ -88,13 +96,13 @@ __global__ void rms_norm_kernel( Additional optimizations we can make in this case are packed and vectorized operations, which help with the memory latency bottleneck. */ -template +template __global__ std::enable_if_t<(width > 0) && _typeConvert::exists> fused_add_rms_norm_kernel( scalar_t* __restrict__ input, // [..., hidden_size] const int64_t input_stride, scalar_t* __restrict__ residual, // [..., hidden_size] - const scalar_t* __restrict__ weight, // [hidden_size] + const scalar_t* __restrict__ weight, // [hidden_size], null if !HasWeight const float epsilon, const int num_tokens, const int hidden_size) { // Sanity checks on our vector struct and type-punned pointer arithmetic static_assert(std::is_pod_v<_f16Vec>); @@ -136,13 +144,21 @@ fused_add_rms_norm_kernel( int id = blockIdx.x * vec_hidden_size + idx; int64_t strided_id = blockIdx.x * vec_input_stride + idx; _f16Vec res = residual_v[id]; - _f16Vec w = weight_v[idx]; _f16Vec out; using Converter = _typeConvert; + if constexpr (HasWeight) { + _f16Vec w = weight_v[idx]; +#pragma unroll + for (int j = 0; j < width; ++j) { + float x = Converter::convert(res.data[j]); + out.data[j] = Converter::convert(x * s_variance) * w.data[j]; + } + } else { #pragma unroll - for (int j = 0; j < width; ++j) { - float x = Converter::convert(res.data[j]); - out.data[j] = Converter::convert(x * s_variance) * w.data[j]; + for (int j = 0; j < width; ++j) { + float x = Converter::convert(res.data[j]); + out.data[j] = Converter::convert(x * s_variance); + } } input_v[strided_id] = out; } @@ -151,13 +167,13 @@ fused_add_rms_norm_kernel( /* Generic fused_add_rms_norm_kernel The width field is not used here but necessary for other specializations. */ -template +template __global__ std::enable_if_t<(width == 0) || !_typeConvert::exists> fused_add_rms_norm_kernel( scalar_t* __restrict__ input, // [..., hidden_size] const int64_t input_stride, scalar_t* __restrict__ residual, // [..., hidden_size] - const scalar_t* __restrict__ weight, // [hidden_size] + const scalar_t* __restrict__ weight, // [hidden_size], null if !HasWeight const float epsilon, const int num_tokens, const int hidden_size) { __shared__ float s_variance; float variance = 0.0f; @@ -181,23 +197,29 @@ fused_add_rms_norm_kernel( for (int idx = threadIdx.x; idx < hidden_size; idx += blockDim.x) { float x = (float)residual[blockIdx.x * hidden_size + idx]; - input[blockIdx.x * input_stride + idx] = - (scalar_t)(x * s_variance) * weight[idx]; + if constexpr (HasWeight) { + input[blockIdx.x * input_stride + idx] = + (scalar_t)(x * s_variance) * weight[idx]; + } else { + input[blockIdx.x * input_stride + idx] = (scalar_t)(x * s_variance); + } } } } // namespace vllm -void rms_norm(torch::stable::Tensor& out, // [..., hidden_size] - torch::stable::Tensor& input, // [..., hidden_size] - torch::stable::Tensor& weight, // [hidden_size] +void rms_norm(torch::stable::Tensor& out, // [..., hidden_size] + torch::stable::Tensor& input, // [..., hidden_size] + std::optional weight, // [hidden_size] double epsilon) { STD_TORCH_CHECK(out.is_contiguous()); if (input.stride(-1) != 1) { input = torch::stable::contiguous(input); } STD_TORCH_CHECK(input.stride(-1) == 1); - STD_TORCH_CHECK(weight.is_contiguous()); + if (weight.has_value()) { + STD_TORCH_CHECK(weight->is_contiguous()); + } int hidden_size = input.size(-1); @@ -215,46 +237,69 @@ void rms_norm(torch::stable::Tensor& out, // [..., hidden_size] const torch::stable::accelerator::DeviceGuard device_guard( input.get_device_index()); const cudaStream_t stream = get_current_cuda_stream(); + const bool has_weight = weight.has_value(); VLLM_STABLE_DISPATCH_RANK234(num_dims, [&] { VLLM_STABLE_DISPATCH_FLOATING_TYPES( input.scalar_type(), "rms_norm_kernel", [&] { + const scalar_t* weight_ptr = + has_weight ? weight->const_data_ptr() : nullptr; const int calculated_vec_size = std::gcd(16 / sizeof(scalar_t), hidden_size); const int block_size = std::min(hidden_size / calculated_vec_size, max_block_size); dim3 block(block_size); VLLM_STABLE_DISPATCH_VEC_SIZE(calculated_vec_size, [&] { - vllm::rms_norm_kernel - <<>>( - out.mutable_data_ptr(), - input.const_data_ptr(), input_stride_d2, - input_stride_d3, input_stride_d4, input_shape_d2, - input_shape_d3, weight.const_data_ptr(), epsilon, - num_tokens, hidden_size); + if (has_weight) { + vllm::rms_norm_kernel + <<>>( + out.mutable_data_ptr(), + input.const_data_ptr(), input_stride_d2, + input_stride_d3, input_stride_d4, input_shape_d2, + input_shape_d3, weight_ptr, epsilon, num_tokens, + hidden_size); + } else { + vllm::rms_norm_kernel + <<>>( + out.mutable_data_ptr(), + input.const_data_ptr(), input_stride_d2, + input_stride_d3, input_stride_d4, input_shape_d2, + input_shape_d3, weight_ptr, epsilon, num_tokens, + hidden_size); + } }); }); }); } -#define LAUNCH_FUSED_ADD_RMS_NORM(width) \ - VLLM_STABLE_DISPATCH_FLOATING_TYPES( \ - input.scalar_type(), "fused_add_rms_norm_kernel", [&] { \ - vllm::fused_add_rms_norm_kernel \ - <<>>( \ - input.mutable_data_ptr(), input_stride, \ - residual.mutable_data_ptr(), \ - weight.const_data_ptr(), epsilon, num_tokens, \ - hidden_size); \ +#define LAUNCH_FUSED_ADD_RMS_NORM(width, has_weight) \ + VLLM_STABLE_DISPATCH_FLOATING_TYPES( \ + input.scalar_type(), "fused_add_rms_norm_kernel", [&] { \ + if (has_weight) { \ + vllm::fused_add_rms_norm_kernel \ + <<>>( \ + input.mutable_data_ptr(), input_stride, \ + residual.mutable_data_ptr(), \ + weight->const_data_ptr(), epsilon, num_tokens, \ + hidden_size); \ + } else { \ + vllm::fused_add_rms_norm_kernel \ + <<>>( \ + input.mutable_data_ptr(), input_stride, \ + residual.mutable_data_ptr(), nullptr, epsilon, \ + num_tokens, hidden_size); \ + } \ }); void fused_add_rms_norm(torch::stable::Tensor& input, // [..., hidden_size] torch::stable::Tensor& residual, // [..., hidden_size] - torch::stable::Tensor& weight, // [hidden_size] + std::optional weight, double epsilon) { - STD_TORCH_CHECK(weight.scalar_type() == input.scalar_type()); STD_TORCH_CHECK(input.scalar_type() == residual.scalar_type()); STD_TORCH_CHECK(residual.is_contiguous()); - STD_TORCH_CHECK(weight.is_contiguous()); + if (weight.has_value()) { + STD_TORCH_CHECK(weight->scalar_type() == input.scalar_type()); + STD_TORCH_CHECK(weight->is_contiguous()); + } int hidden_size = input.size(-1); int64_t input_stride = input.stride(-2); int num_tokens = input.numel() / hidden_size; @@ -269,30 +314,33 @@ void fused_add_rms_norm(torch::stable::Tensor& input, // [..., hidden_size] const torch::stable::accelerator::DeviceGuard device_guard( input.get_device_index()); const cudaStream_t stream = get_current_cuda_stream(); - /*If the tensor types are FP16/BF16, try to use the optimized kernel - with packed + vectorized ops. - Max optimization is achieved with a width-8 vector of FP16/BF16s - since we can load at most 128 bits at once in a global memory op. - However, this requires each tensor's data to be aligned to 16 - bytes. - */ + constexpr int vector_width = 8; + constexpr int req_alignment_bytes = vector_width * 2; auto inp_ptr = reinterpret_cast(input.data_ptr()); auto res_ptr = reinterpret_cast(residual.data_ptr()); - auto wt_ptr = reinterpret_cast(weight.data_ptr()); - constexpr int vector_width = 8; - constexpr int req_alignment_bytes = - vector_width * 2; // vector_width * sizeof(bfloat16 or float16) (float32 - // falls back to non-vectorized version anyway) - bool ptrs_are_aligned = inp_ptr % req_alignment_bytes == 0 && - res_ptr % req_alignment_bytes == 0 && - wt_ptr % req_alignment_bytes == 0; bool offsets_are_multiple_of_vector_width = hidden_size % vector_width == 0 && input_stride % vector_width == 0; bool batch_invariant_launch = vllm::vllm_is_batch_invariant(); - if (ptrs_are_aligned && offsets_are_multiple_of_vector_width && - !batch_invariant_launch) { - LAUNCH_FUSED_ADD_RMS_NORM(8); + const bool has_weight = weight.has_value(); + if (has_weight) { + auto wt_ptr = reinterpret_cast(weight->data_ptr()); + bool ptrs_are_aligned = inp_ptr % req_alignment_bytes == 0 && + res_ptr % req_alignment_bytes == 0 && + wt_ptr % req_alignment_bytes == 0; + if (ptrs_are_aligned && offsets_are_multiple_of_vector_width && + !batch_invariant_launch) { + LAUNCH_FUSED_ADD_RMS_NORM(8, true); + } else { + LAUNCH_FUSED_ADD_RMS_NORM(0, true); + } } else { - LAUNCH_FUSED_ADD_RMS_NORM(0); + bool ptrs_are_aligned = inp_ptr % req_alignment_bytes == 0 && + res_ptr % req_alignment_bytes == 0; + if (ptrs_are_aligned && offsets_are_multiple_of_vector_width && + !batch_invariant_launch) { + LAUNCH_FUSED_ADD_RMS_NORM(8, false); + } else { + LAUNCH_FUSED_ADD_RMS_NORM(0, false); + } } } diff --git a/csrc/libtorch_stable/moe/dsv3_router_gemm_entry.cu b/csrc/libtorch_stable/moe/dsv3_router_gemm_entry.cu index 1de1a319e488..53a64fa8c138 100644 --- a/csrc/libtorch_stable/moe/dsv3_router_gemm_entry.cu +++ b/csrc/libtorch_stable/moe/dsv3_router_gemm_entry.cu @@ -144,8 +144,7 @@ void dsv3_router_gemm( "output must be float32 or bf16"); const int sm = getSMVersion(); - STD_TORCH_CHECK(sm >= 90 && sm <= 103, - "required SM_103 >= CUDA ARCH >= SM_90"); + STD_TORCH_CHECK(sm >= 90, "required CUDA ARCH >= SM_90"); const cudaStream_t stream = get_current_cuda_stream(mat_a.get_device_index()); diff --git a/csrc/libtorch_stable/ops.h b/csrc/libtorch_stable/ops.h index 6ebec954497e..9efc12e9f495 100644 --- a/csrc/libtorch_stable/ops.h +++ b/csrc/libtorch_stable/ops.h @@ -3,6 +3,9 @@ #include #include +#include +#include + void per_token_group_quant_fp8(const torch::stable::Tensor& input, torch::stable::Tensor& output_q, torch::stable::Tensor& output_s, @@ -185,11 +188,12 @@ torch::stable::Tensor hadacore_transform(torch::stable::Tensor& x, // Layernorm kernels (shared CUDA/ROCm) void rms_norm(torch::stable::Tensor& out, torch::stable::Tensor& input, - torch::stable::Tensor& weight, double epsilon); + std::optional weight, double epsilon); void fused_add_rms_norm(torch::stable::Tensor& input, torch::stable::Tensor& residual, - torch::stable::Tensor& weight, double epsilon); + std::optional weight, + double epsilon); // Layernorm-quant kernels (shared CUDA/ROCm) void rms_norm_static_fp8_quant(torch::stable::Tensor& out, @@ -281,6 +285,25 @@ minimax_allreduce_rms_qk(torch::stable::Tensor qkv, int64_t const nranks, double const eps); #endif +// Horizontally-fused MiniMax-M3 QK-norm + partial NeoX RoPE (+ optional KV / +// index-cache insert). Dense layer: norm+RoPE only; sparse layer: also packs +// the index branch and scatters k/v/index_k into their paged caches. +void fused_minimax_m3_qknorm_rope_kv_insert( + torch::stable::Tensor& qkv, torch::stable::Tensor const& q_norm_weight, + torch::stable::Tensor const& k_norm_weight, + torch::stable::Tensor const& cos_sin_cache, + torch::stable::Tensor const& positions, int64_t num_heads, + int64_t num_kv_heads, int64_t rotary_dim, double eps, + std::optional index_q_norm_weight, + std::optional index_k_norm_weight, + int64_t num_index_heads, std::optional slot_mapping, + std::optional index_slot_mapping, + std::optional kv_cache, + std::optional index_cache, int64_t block_size, + std::optional q_out, + std::optional index_q_out, + const std::string& kv_cache_dtype); + // Sampler kernels (shared CUDA/ROCm) void apply_repetition_penalties_( torch::stable::Tensor& logits, const torch::stable::Tensor& prompt_mask, @@ -346,7 +369,8 @@ void free_shared_buffer(int64_t buffer); // Activation kernels (shared CUDA/ROCm) void silu_and_mul(torch::stable::Tensor& out, torch::stable::Tensor& input); void silu_and_mul_clamp(torch::stable::Tensor& out, - torch::stable::Tensor& input, double limit); + torch::stable::Tensor& input, double limit, + double alpha = 1.0, double beta = 0.0); void mul_and_silu(torch::stable::Tensor& out, torch::stable::Tensor& input); void gelu_and_mul(torch::stable::Tensor& out, torch::stable::Tensor& input); void gelu_tanh_and_mul(torch::stable::Tensor& out, @@ -397,35 +421,6 @@ torch::stable::Tensor gptq_gemm(torch::stable::Tensor a, void gptq_shuffle(torch::stable::Tensor q_weight, torch::stable::Tensor q_perm, int64_t bit); -// GGML kernels (shared CUDA/ROCm) -torch::stable::Tensor ggml_dequantize( - torch::stable::Tensor W, int64_t type, int64_t m, int64_t n, - std::optional const& dtype); - -torch::stable::Tensor ggml_mul_mat_vec_a8(torch::stable::Tensor W, - torch::stable::Tensor X, int64_t type, - int64_t row); - -torch::stable::Tensor ggml_mul_mat_a8(torch::stable::Tensor W, - torch::stable::Tensor X, int64_t type, - int64_t row); - -torch::stable::Tensor ggml_moe_a8(torch::stable::Tensor X, - torch::stable::Tensor W, - torch::stable::Tensor sorted_token_ids, - torch::stable::Tensor expert_ids, - torch::stable::Tensor num_tokens_post_padded, - int64_t type, int64_t row, int64_t top_k, - int64_t tokens); - -torch::stable::Tensor ggml_moe_a8_vec(torch::stable::Tensor X, - torch::stable::Tensor W, - torch::stable::Tensor topk_ids, - int64_t top_k, int64_t type, int64_t row, - int64_t tokens); - -int64_t ggml_moe_get_block_size(int64_t type); - void paged_attention_v1( torch::stable::Tensor& out, torch::stable::Tensor& query, torch::stable::Tensor& key_cache, torch::stable::Tensor& value_cache, diff --git a/csrc/libtorch_stable/quantization/fp4/mxfp4_experts_quant.cu b/csrc/libtorch_stable/quantization/fp4/mxfp4_experts_quant.cu index 062f6018653c..20f024bcef51 100644 --- a/csrc/libtorch_stable/quantization/fp4/mxfp4_experts_quant.cu +++ b/csrc/libtorch_stable/quantization/fp4/mxfp4_experts_quant.cu @@ -27,15 +27,24 @@ #include #include "libtorch_stable/torch_utils.h" #include "libtorch_stable/dispatch_utils.h" +#include "libtorch_stable/cutlass_extensions/common.hpp" #include "../../cuda_vec_utils.cuh" #include "cuda_utils.h" #include "nvfp4_utils.cuh" + +#if defined(CUDART_VERSION) && CUDART_VERSION >= 12090 + #define VLLM_MXFP4_EXPERTS_QUANT_SUPPORTED 1 static_assert(CVT_FP4_ELTS_PER_THREAD == 16, "MXFP4 experts quant requires PACK16 mode (CUDA >= 12.9)"); +#else + #define VLLM_MXFP4_EXPERTS_QUANT_SUPPORTED 0 +#endif #include "libtorch_stable/launch_bounds_utils.h" +#if VLLM_MXFP4_EXPERTS_QUANT_SUPPORTED + namespace vllm { // MXFP4 block size constants @@ -104,7 +113,7 @@ __global__ void __launch_bounds__(512, VLLM_BLOCKS_PER_SM(512)) &input_offset_by_experts[chunk_start + 12])); local_offsets[16] = __ldca(&input_offset_by_experts[chunk_start + 16]); -#pragma unroll + #pragma unroll for (int i = 0; i < 16; i++) { if (rowIdx >= local_offsets[i] && rowIdx < local_offsets[i + 1]) { rowIdx_in_expert = rowIdx - local_offsets[i]; @@ -309,14 +318,14 @@ void mxfp4_quant_impl(void* output, void* output_scale, void* input, } // namespace vllm -/*Quantization entry for mxfp4 experts quantization*/ -#define CHECK_TH_CUDA(x, m) \ - STD_TORCH_CHECK(x.is_cuda(), m, "must be a CUDA tensor") -#define CHECK_CONTIGUOUS(x, m) \ - STD_TORCH_CHECK(x.is_contiguous(), m, "must be contiguous") -#define CHECK_INPUT(x, m) \ - CHECK_TH_CUDA(x, m); \ - CHECK_CONTIGUOUS(x, m); + /*Quantization entry for mxfp4 experts quantization*/ + #define CHECK_TH_CUDA(x, m) \ + STD_TORCH_CHECK(x.is_cuda(), m, "must be a CUDA tensor") + #define CHECK_CONTIGUOUS(x, m) \ + STD_TORCH_CHECK(x.is_contiguous(), m, "must be contiguous") + #define CHECK_INPUT(x, m) \ + CHECK_TH_CUDA(x, m); \ + CHECK_CONTIGUOUS(x, m); constexpr auto HALF = torch::headeronly::ScalarType::Half; constexpr auto BF16 = torch::headeronly::ScalarType::BFloat16; @@ -364,12 +373,28 @@ static void validate_mxfp4_experts_quant_inputs( STD_TORCH_CHECK(output_scale.size(1) * 4 == padded_k); } +#endif // VLLM_MXFP4_EXPERTS_QUANT_SUPPORTED + +static bool mxfp4_experts_quant_sm_supported(int64_t cuda_device_capability) { +#if VLLM_MXFP4_EXPERTS_QUANT_SUPPORTED + return cuda_device_capability >= 100 && cuda_device_capability < 120; +#else + return false; +#endif +} + void mxfp4_experts_quant( torch::stable::Tensor& output, torch::stable::Tensor& output_scale, torch::stable::Tensor const& input, torch::stable::Tensor const& input_offset_by_experts, torch::stable::Tensor const& output_scale_offset_by_experts, int64_t n_experts) { +#if VLLM_MXFP4_EXPERTS_QUANT_SUPPORTED + int32_t sm = get_sm_version_num(); + STD_TORCH_CHECK(mxfp4_experts_quant_sm_supported(sm), + "No compiled MXFP4 experts quant kernel for SM ", sm, + ". Recompile with SM10x/11x FP4 support and CUDA >= 12.9."); + auto m_topk = input.size(0); auto k = input.size(1); @@ -390,6 +415,10 @@ void mxfp4_experts_quant( output_scale_offset_by_experts.data_ptr(), m_topk, k, n_experts, stream); }); +#else + STD_TORCH_CHECK_NOT_IMPLEMENTED(false, + "MXFP4 experts quant requires CUDA >= 12.9."); +#endif } void silu_and_mul_mxfp4_experts_quant( @@ -398,6 +427,12 @@ void silu_and_mul_mxfp4_experts_quant( torch::stable::Tensor const& input_offset_by_experts, torch::stable::Tensor const& output_scale_offset_by_experts, int64_t n_experts) { +#if VLLM_MXFP4_EXPERTS_QUANT_SUPPORTED + int32_t sm = get_sm_version_num(); + STD_TORCH_CHECK(mxfp4_experts_quant_sm_supported(sm), + "No compiled SiLU+Mul MXFP4 experts quant kernel for SM ", sm, + ". Recompile with SM10x/11x FP4 support and CUDA >= 12.9."); + auto m_topk = input.size(0); auto k_times_2 = input.size(1); STD_TORCH_CHECK(k_times_2 % 2 == 0, "input width must be even (gate || up)"); @@ -420,13 +455,29 @@ void silu_and_mul_mxfp4_experts_quant( output_scale_offset_by_experts.data_ptr(), m_topk, k, n_experts, stream); }); +#else + STD_TORCH_CHECK_NOT_IMPLEMENTED( + false, "SiLU+Mul MXFP4 experts quant requires CUDA >= 12.9."); +#endif } -// Registered here (not torch_bindings.cpp) because VLLM_GPU_FLAGS is applied -// only under COMPILE_LANGUAGE:CUDA, so ENABLE_NVFP4_SM100 is invisible to -// .cpp files and cannot gate the registration from there. +bool mxfp4_experts_quant_supported(int64_t cuda_device_capability) { + return mxfp4_experts_quant_sm_supported(cuda_device_capability); +} + +STABLE_TORCH_LIBRARY_FRAGMENT(_C, m) { + m.def("mxfp4_experts_quant_supported(int cuda_device_capability) -> bool"); +} + +// Registered here so the CUDA 12.8 stub and CUDA 12.9+ implementation stay +// tied to the same translation unit. STABLE_TORCH_LIBRARY_IMPL(_C, CUDA, m) { m.impl("mxfp4_experts_quant", TORCH_BOX(&mxfp4_experts_quant)); m.impl("silu_and_mul_mxfp4_experts_quant", TORCH_BOX(&silu_and_mul_mxfp4_experts_quant)); } + +STABLE_TORCH_LIBRARY_IMPL(_C, CompositeExplicitAutograd, m) { + m.impl("mxfp4_experts_quant_supported", + TORCH_BOX(&mxfp4_experts_quant_supported)); +} diff --git a/csrc/libtorch_stable/quantization/fp4/nvfp4_utils.cuh b/csrc/libtorch_stable/quantization/fp4/nvfp4_utils.cuh index 0c04f010888d..667138f34873 100644 --- a/csrc/libtorch_stable/quantization/fp4/nvfp4_utils.cuh +++ b/csrc/libtorch_stable/quantization/fp4/nvfp4_utils.cuh @@ -22,15 +22,15 @@ #include "../../cuda_vec_utils.cuh" -#if defined(NVFP4_ENABLE_ELTS16) && defined(CUDA_VERSION) && \ - CUDA_VERSION >= 12090 +#if defined(NVFP4_ENABLE_ELTS16) && defined(CUDART_VERSION) && \ + CUDART_VERSION >= 12090 #define ELTS_PER_THREAD 16 + #define CVT_FP4_PACK16 1 constexpr int CVT_FP4_ELTS_PER_THREAD = 16; -constexpr bool CVT_FP4_PACK16 = true; #else #define ELTS_PER_THREAD 8 + #define CVT_FP4_PACK16 0 constexpr int CVT_FP4_ELTS_PER_THREAD = 8; -constexpr bool CVT_FP4_PACK16 = false; #endif constexpr int CVT_FP4_SF_VEC_SIZE = 16; @@ -237,21 +237,30 @@ __device__ __forceinline__ fp4_packed_t cvt_warp_fp16_to_fp4( // Get the final absolute maximum values. float vecMax = float(__hmax(localMax.x, localMax.y)); - // Get the SF (max value of the vector / max value of e2m1). - // maximum value of e2m1 = 6.0. - // TODO: use half as compute data type. - float SFValue = SFScaleVal * (vecMax * reciprocal_approximate_ftz(6.0f)); // 8 bits representation of the SF. + float SFValue; uint8_t fp8SFVal; - // Write the SF to global memory (STG.8). + if constexpr (UE8M0_SF) { - // Extract the 8 exponent bits from float32. - // float 32bits = 1 sign bit + 8 exponent bits + 23 mantissa bits. - uint32_t tmp = reinterpret_cast(SFValue) >> 23; - fp8SFVal = tmp & 0xff; - // Convert back to fp32. - reinterpret_cast(SFValue) = tmp << 23; + // OCP MX spec E8M0 scale computation (MXFP4 path): + // scale_exp = biased_exponent(round_up(vecMax)) - 2 + // -2 because max E2M1 value is 6.0 ≈ 2^2.58; we use 2^2=4 as the + // safe divisor so that max_val / scale <= 6.0 for values near 2^n. + uint32_t max_bits = __float_as_uint(vecMax); + // Add rounding bias at mantissa bit 21 (equivalent to bf16 val_to_add=32 + // at bit 5). Threshold: values with mantissa >= 0.75 (i.e. >= 1.75*2^n) + // round up to the next power of 2. + uint32_t rounded_bits = (max_bits + (1u << 21)) & 0xFF800000u; + uint32_t biased_exp = (rounded_bits >> 23) & 0xFFu; + uint32_t scale_exp = (biased_exp > 2u) ? (biased_exp - 2u) : 0u; + scale_exp = min(scale_exp, 254u); + fp8SFVal = static_cast(scale_exp); + // Reconstruct scale as float32: scale = 2^(scale_exp - 127) + uint32_t sf_bits = scale_exp << 23; + SFValue = __uint_as_float(sf_bits); } else { + // NVFP4 path: scale = max / 6.0, stored as E4M3. + SFValue = SFScaleVal * (vecMax * reciprocal_approximate_ftz(6.0f)); // Here SFValue is always positive, so E4M3 is the same as UE4M3. __nv_fp8_e4m3 tmp = __nv_fp8_e4m3(SFValue); reinterpret_cast<__nv_fp8_e4m3&>(fp8SFVal) = tmp; @@ -262,13 +271,21 @@ __device__ __forceinline__ fp4_packed_t cvt_warp_fp16_to_fp4( // Write the SF to global memory (STG.8). if (SFout) *SFout = fp8SFVal; - // Get the output scale. - // Recipe: final_scale = reciprocal(fp32(fp8(SFValue * SFScaleVal))) * - // reciprocal(SFScaleVal)) - float outputScale = - SFValue != 0.0f ? reciprocal_approximate_ftz( + // Get the output scale (= 1 / SFValue for the MXFP4/UE8M0 path where + // SFScaleVal=1). Use exact division for UE8M0 to ensure bit-exact scaling + // that matches the reference QDQ implementation (dividing by a power-of-2 + // scale is exact in IEEE 754). + float outputScale; + if constexpr (UE8M0_SF) { + // SFValue is always a power of 2 for UE8M0, so 1/SFValue is exact. + outputScale = SFValue != 0.0f ? (1.0f / SFValue) : 0.0f; + } else { + // NVFP4 path: use fast approximate reciprocal (original behavior). + outputScale = SFValue != 0.0f + ? reciprocal_approximate_ftz( SFValue * reciprocal_approximate_ftz(SFScaleVal)) : 0.0f; + } // Convert the input to float. float2 fp2Vals[CVT_FP4_ELTS_PER_THREAD / 2]; diff --git a/csrc/libtorch_stable/quantization/gguf/dequantize.cuh b/csrc/libtorch_stable/quantization/gguf/dequantize.cuh deleted file mode 100644 index e18577da5698..000000000000 --- a/csrc/libtorch_stable/quantization/gguf/dequantize.cuh +++ /dev/null @@ -1,571 +0,0 @@ -// copied and adapted from https://github.com/ggerganov/llama.cpp/blob/b2899/ggml-cuda/convert.cu -// Dequant functions -static __device__ __forceinline__ void dequantize_q4_0(const void * vx, const int ib, const int iqs, dfloat2 & v){ - const block_q4_0 * x = (const block_q4_0 *) vx; - - const dfloat d = x[ib].d; - - const int vui = x[ib].qs[iqs]; - - v.x = __int2half_rn(vui & 0xF); - v.y = __int2half_rn(vui >> 4); - - v = __hsub2(v, __floats2half2_rn(8.0f, 8.0f)); - v = __hmul2(v, {d, d}); -} - -static __device__ __forceinline__ void dequantize_q4_1(const void * vx, const int ib, const int iqs, dfloat2 & v){ - const block_q4_1 * x = (const block_q4_1 *) vx; - - const dfloat d = __low2half(x[ib].dm); - const dfloat m = __high2half(x[ib].dm); - - const int vui = x[ib].qs[iqs]; - - v.x = __int2half_rn(vui & 0xF); - v.y = __int2half_rn(vui >> 4); - - v = __hmul2(v, {d, d}); - v = __hadd2(v, {m, m}); -} - -static __device__ __forceinline__ void dequantize_q5_0(const void * vx, const int ib, const int iqs, dfloat2 & v){ - const block_q5_0 * x = (const block_q5_0 *) vx; - - const dfloat d = x[ib].d; - - uint32_t qh; - memcpy(&qh, x[ib].qh, sizeof(qh)); - - const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10; - const int xh_1 = ((qh >> (iqs + 12)) ) & 0x10; - - v.x = __int2half_rn((x[ib].qs[iqs] & 0xf) | xh_0); - v.y = __int2half_rn((x[ib].qs[iqs] >> 4) | xh_1); - - v = __hsub2(v, __floats2half2_rn(16.0f, 16.0f)); - v = __hmul2(v, {d, d}); -} - -static __device__ __forceinline__ void dequantize_q5_1(const void * vx, const int ib, const int iqs, dfloat2 & v){ - const block_q5_1 * x = (const block_q5_1 *) vx; - - const dfloat d = __low2half(x[ib].dm); - const dfloat m = __high2half(x[ib].dm); - - uint32_t qh; - memcpy(&qh, x[ib].qh, sizeof(qh)); - - const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10; - const int xh_1 = ((qh >> (iqs + 12)) ) & 0x10; - - v.x = __int2half_rn((x[ib].qs[iqs] & 0xf) | xh_0); - v.y = __int2half_rn((x[ib].qs[iqs] >> 4) | xh_1); - - v = __hmul2(v, {d, d}); - v = __hadd2(v, {m, m}); -} - -static __device__ __forceinline__ void dequantize_q8_0(const void * vx, const int ib, const int iqs, dfloat2 & v){ - const block_q8_0 * x = (const block_q8_0 *) vx; - - const dfloat d = x[ib].d; - - v.x = __int2half_rn(x[ib].qs[iqs + 0]); - v.y = __int2half_rn(x[ib].qs[iqs + 1]); - - v = __hmul2(v, {d, d}); -} - -template -static __global__ void dequantize_block(const void * __restrict__ vx, dst_t * __restrict__ y, const int64_t k) { - const int64_t i = 2*((int64_t)blockDim.x*blockIdx.x + threadIdx.x); - - if (i >= k) { - return; - } - - const int ib = i/qk; // block index - const int iqs = (i%qk)/qr; // quant index - const int iybs = i - i%qk; // y block start index - const int y_offset = qr == 1 ? 1 : qk/2; - - // dequantize - dfloat2 v; - dequantize_kernel(vx, ib, iqs, v); - - y[iybs + iqs + 0] = convert_from_half(v.x); - y[iybs + iqs + y_offset] = convert_from_half(v.y); -} - -template -static __global__ void dequantize_block_q2_K(const void * __restrict__ vx, dst_t * __restrict__ yy) { - - const auto i = blockIdx.x; - const block_q2_K * x = (const block_q2_K *) vx; - - const auto tid = threadIdx.x; - const int n = tid/32; - const int l = tid - 32*n; - const int is = 8*n + l/16; - - const uint8_t q = x[i].qs[32*n + l]; - dst_t * y = yy + i*QK_K + 128*n; - - half dall = __low2half(x[i].dm); - half dmin = __high2half(x[i].dm); - y[l+ 0] = convert_from_half(__hsub(__hmul(dall, __int2half_rn((x[i].scales[is+0] & 0xF) * ((q >> 0) & 3))), __hmul(dmin, __int2half_rn(x[i].scales[is+0] >> 4)))); - y[l+32] = convert_from_half(__hsub(__hmul(dall, __int2half_rn((x[i].scales[is+2] & 0xF) * ((q >> 2) & 3))), __hmul(dmin, __int2half_rn(x[i].scales[is+2] >> 4)))); - y[l+64] = convert_from_half(__hsub(__hmul(dall, __int2half_rn((x[i].scales[is+4] & 0xF) * ((q >> 4) & 3))), __hmul(dmin, __int2half_rn(x[i].scales[is+4] >> 4)))); - y[l+96] = convert_from_half(__hsub(__hmul(dall, __int2half_rn((x[i].scales[is+6] & 0xF) * ((q >> 6) & 3))), __hmul(dmin, __int2half_rn(x[i].scales[is+6] >> 4)))); -} - -template -static __global__ void dequantize_block_q3_K(const void * __restrict__ vx, dst_t * __restrict__ yy) { - - const auto i = blockIdx.x; - const block_q3_K * x = (const block_q3_K *) vx; - - const auto r = threadIdx.x/4; - const int tid = r/2; - const int is0 = r%2; - const int l0 = 16*is0 + 4*(threadIdx.x%4); - const int n = tid / 4; - const int j = tid - 4*n; - - uint8_t m = 1 << (4*n + j); - int is = 8*n + 2*j + is0; - int shift = 2*j; - - int8_t us = is < 4 ? (x[i].scales[is-0] & 0xF) | (((x[i].scales[is+8] >> 0) & 3) << 4) : - is < 8 ? (x[i].scales[is-0] & 0xF) | (((x[i].scales[is+4] >> 2) & 3) << 4) : - is < 12 ? (x[i].scales[is-8] >> 4) | (((x[i].scales[is+0] >> 4) & 3) << 4) : - (x[i].scales[is-8] >> 4) | (((x[i].scales[is-4] >> 6) & 3) << 4); - half d_all = x[i].d; - half dl = __hmul(d_all, __int2half_rn(us - 32)); - - dst_t * y = yy + i*QK_K + 128*n + 32*j; - const uint8_t * q = x[i].qs + 32*n; - const uint8_t * hm = x[i].hmask; - - for (int l = l0; l < l0+4; ++l) { - y[l] = convert_from_half(__hmul(dl, __int2half_rn((int8_t)((q[l] >> shift) & 3) - ((hm[l] & m) ? 0 : 4)))); - } -} - -static inline __device__ void get_scale_min_k4(int j, const uint8_t * q, uint8_t & d, uint8_t & m) { - if (j < 4) { - d = q[j] & 63; m = q[j + 4] & 63; - } else { - d = (q[j+4] & 0xF) | ((q[j-4] >> 6) << 4); - m = (q[j+4] >> 4) | ((q[j-0] >> 6) << 4); - } -} - -template -static __global__ void dequantize_block_q4_K(const void * __restrict__ vx, dst_t * __restrict__ yy) { - const block_q4_K * x = (const block_q4_K *) vx; - - const auto i = blockIdx.x; - - // assume 32 threads - const auto tid = threadIdx.x; - const int il = tid/8; - const int ir = tid%8; - const int is = 2*il; - const int n = 4; - - dst_t * y = yy + i*QK_K + 64*il + n*ir; - - const half dall = __low2half(x[i].dm); - const half dmin = __high2half(x[i].dm); - - const uint8_t * q = x[i].qs + 32*il + n*ir; - - uint8_t sc, m; - get_scale_min_k4(is + 0, x[i].scales, sc, m); - const half d1 = __hmul(dall, __int2half_rn(sc)); - const half m1 = __hmul(dmin, __int2half_rn(m)); - get_scale_min_k4(is + 1, x[i].scales, sc, m); - const half d2 = __hmul(dall, __int2half_rn(sc)); - const half m2 = __hmul(dmin, __int2half_rn(m)); - for (int l = 0; l < n; ++l) { - y[l + 0] = convert_from_half(__hsub(__hmul(d1, __int2half_rn(q[l] & 0xF)), m1)); - y[l +32] = convert_from_half(__hsub(__hmul(d2, __int2half_rn(q[l] >> 4)), m2)); - } -} - -template -static __global__ void dequantize_block_q5_K(const void * __restrict__ vx, dst_t * __restrict__ yy) { - const block_q5_K * x = (const block_q5_K *) vx; - - const auto i = blockIdx.x; - - // assume 64 threads - this is very slightly better than the one below - const auto tid = threadIdx.x; - const int il = tid/16; // il is in 0...3 - const int ir = tid%16; // ir is in 0...15 - const int is = 2*il; // is is in 0...6 - - dst_t * y = yy + i*QK_K + 64*il + 2*ir; - - const half dall = __low2half(x[i].dm); - const half dmin = __high2half(x[i].dm); - - const uint8_t * ql = x[i].qs + 32*il + 2*ir; - const uint8_t * qh = x[i].qh + 2*ir; - - uint8_t sc, m; - get_scale_min_k4(is + 0, x[i].scales, sc, m); - const half d1 = __hmul(dall, __int2half_rn(sc)); const half m1 = __hmul(dmin, __int2half_rn(m)); - get_scale_min_k4(is + 1, x[i].scales, sc, m); - const half d2 = __hmul(dall, __int2half_rn(sc)); const half m2 = __hmul(dmin, __int2half_rn(m)); - - uint8_t hm = 1 << (2*il); - y[ 0] = convert_from_half(__hsub(__hmul(d1, __int2half_rn((ql[0] & 0xF) + (qh[0] & hm ? 16 : 0))), m1)); - y[ 1] = convert_from_half(__hsub(__hmul(d1, __int2half_rn((ql[1] & 0xF) + (qh[1] & hm ? 16 : 0))), m1)); - hm <<= 1; - y[32] = convert_from_half(__hsub(__hmul(d2, __int2half_rn((ql[0] >> 4) + (qh[0] & hm ? 16 : 0))), m2)); - y[33] = convert_from_half(__hsub(__hmul(d2, __int2half_rn((ql[1] >> 4) + (qh[1] & hm ? 16 : 0))), m2)); -} - -template -static __global__ void dequantize_block_q6_K(const void * __restrict__ vx, dst_t * __restrict__ yy) { - const block_q6_K * x = (const block_q6_K *) vx; - - const auto i = blockIdx.x; - - // assume 64 threads - this is very slightly better than the one below - const auto tid = threadIdx.x; - const int ip = tid/32; // ip is 0 or 1 - const int il = tid - 32*ip; // 0...32 - const int is = 8*ip + il/16; - - dst_t * y = yy + i*QK_K + 128*ip + il; - - const half d = x[i].d; - - const uint8_t * ql = x[i].ql + 64*ip + il; - const uint8_t qh = x[i].qh[32*ip + il]; - const int8_t * sc = x[i].scales + is; - - y[ 0] = convert_from_half(__hmul(d, __int2half_rn(sc[0] * ((int8_t)((ql[ 0] & 0xF) | (((qh >> 0) & 3) << 4)) - 32)))); - y[32] = convert_from_half(__hmul(d, __int2half_rn(sc[2] * ((int8_t)((ql[32] & 0xF) | (((qh >> 2) & 3) << 4)) - 32)))); - y[64] = convert_from_half(__hmul(d, __int2half_rn(sc[4] * ((int8_t)((ql[ 0] >> 4) | (((qh >> 4) & 3) << 4)) - 32)))); - y[96] = convert_from_half(__hmul(d, __int2half_rn(sc[6] * ((int8_t)((ql[32] >> 4) | (((qh >> 6) & 3) << 4)) - 32)))); -} - -template -static __global__ void dequantize_block_iq2_xxs(const void * __restrict__ vx, dst_t * __restrict__ yy) { - - const auto i = blockIdx.x; - const block_iq2_xxs * x = (const block_iq2_xxs *) vx; - - const auto tid = threadIdx.x; - const int il = tid/8; // 0...3 - const int ib = tid%8; // 0...7 - dst_t * y = yy + i*QK_K + 32*ib + 8*il; - const uint16_t * q2 = x[i].qs + 4*ib; - const uint8_t * aux8 = (const uint8_t *)q2; - const uint8_t * grid = (const uint8_t *)(iq2xxs_grid + aux8[il]); - const uint32_t aux32 = q2[2] | (q2[3] << 16); - const float d = __half2float(x[i].d) * (0.5f + (aux32 >> 28)) * 0.25f; - const uint8_t signs = ksigns_iq2xs[(aux32 >> 7*il) & 127]; - for (int j = 0; j < 8; ++j) y[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); -} - -template -static __global__ void dequantize_block_iq2_xs(const void * __restrict__ vx, dst_t * __restrict__ yy) { - - const auto i = blockIdx.x; - const block_iq2_xs * x = (const block_iq2_xs *) vx; - - const auto tid = threadIdx.x; - const int il = tid/8; // 0...3 - const int ib = tid%8; // 0...7 - dst_t * y = yy + i*QK_K + 32*ib + 8*il; - const uint16_t * q2 = x[i].qs + 4*ib; - const uint8_t * grid = (const uint8_t *)(iq2xs_grid + (q2[il] & 511)); - const float d = __half2float(x[i].d) * (0.5f + ((x[i].scales[ib] >> 4*(il/2)) & 0xf)) * 0.25f; - const uint8_t signs = ksigns_iq2xs[q2[il] >> 9]; - for (int j = 0; j < 8; ++j) y[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); - -} - -template -static __global__ void dequantize_block_iq2_s(const void * __restrict__ vx, dst_t * __restrict__ yy) { - - const auto i = blockIdx.x; - const block_iq2_s * x = (const block_iq2_s *) vx; - - const auto tid = threadIdx.x; - const int il = tid/8; // 0...3 - const int ib = tid%8; // 0...7 - dst_t * y = yy + i*QK_K + 32*ib + 8*il; - const uint8_t * grid = (const uint8_t *)(iq2s_grid + (x[i].qs[4*ib+il] | ((x[i].qh[ib] << (8-2*il)) & 0x300))); - const float d = __half2float(x[i].d) * (0.5f + ((x[i].scales[ib] >> 4*(il/2)) & 0xf)) * 0.25f; - const uint8_t signs = x[i].qs[QK_K/8+4*ib+il]; - for (int j = 0; j < 8; ++j) y[j] = d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); -} - -template -static __global__ void dequantize_block_iq3_xxs(const void * __restrict__ vx, dst_t * __restrict__ yy) { - - const auto i = blockIdx.x; - const block_iq3_xxs * x = (const block_iq3_xxs *) vx; - - const auto tid = threadIdx.x; - const int il = tid/8; // 0...3 - const int ib = tid%8; // 0...7 - dst_t * y = yy + i*QK_K + 32*ib + 8*il; - const uint8_t * q3 = x[i].qs + 8*ib; - const uint16_t * gas = (const uint16_t *)(x[i].qs + QK_K/4) + 2*ib; - const uint8_t * grid1 = (const uint8_t *)(iq3xxs_grid + q3[2*il+0]); - const uint8_t * grid2 = (const uint8_t *)(iq3xxs_grid + q3[2*il+1]); - const uint32_t aux32 = gas[0] | (gas[1] << 16); - const float d = __half2float(x[i].d) * (0.5f + (aux32 >> 28)) * 0.5f; - const uint8_t signs = ksigns_iq2xs[(aux32 >> 7*il) & 127]; - for (int j = 0; j < 4; ++j) { - y[j+0] = d * grid1[j] * (signs & kmask_iq2xs[j+0] ? -1.f : 1.f); - y[j+4] = d * grid2[j] * (signs & kmask_iq2xs[j+4] ? -1.f : 1.f); - } -} - -template -static __global__ void dequantize_block_iq3_s(const void * __restrict__ vx, dst_t * __restrict__ yy) { - - const auto i = blockIdx.x; - const block_iq3_s * x = (const block_iq3_s *) vx; - - const auto tid = threadIdx.x; - const int il = tid/8; // 0...3 - const int ib = tid%8; // 0...7 - dst_t * y = yy + i*QK_K + 32*ib + 8*il; - const uint8_t * qs = x[i].qs + 8*ib; - const uint8_t * grid1 = (const uint8_t *)(iq3xs_grid + (qs[2*il+0] | ((x[i].qh[ib] << (8-2*il)) & 256))); - const uint8_t * grid2 = (const uint8_t *)(iq3xs_grid + (qs[2*il+1] | ((x[i].qh[ib] << (7-2*il)) & 256))); - const float d = __half2float(x[i].d) * (0.5f + ((x[i].scales[ib/2] >> 4*(ib%2)) & 0xf)) * 0.5f; - const uint8_t signs = x[i].signs[4*ib + il]; - for (int j = 0; j < 4; ++j) { - y[j+0] = d * grid1[j] * (signs & kmask_iq2xs[j+0] ? -1.f : 1.f); - y[j+4] = d * grid2[j] * (signs & kmask_iq2xs[j+4] ? -1.f : 1.f); - } -} - -template -static __global__ void dequantize_block_iq1_s(const void * __restrict__ vx, dst_t * __restrict__ yy) { - - const int64_t i = blockIdx.x; - const block_iq1_s * x = (const block_iq1_s *) vx; - - const int64_t tid = threadIdx.x; - const int64_t il = tid/8; // 0...3 - const int64_t ib = tid%8; // 0...7 - dst_t * y = yy + i*QK_K + 32*ib + 8*il; - const float delta = x[i].qh[ib] & 0x8000 ? -1 - IQ1S_DELTA : -1 + IQ1S_DELTA; - const float d = __half2float(x[i].d) * (2*((x[i].qh[ib] >> 12) & 7) + 1); - uint32_t grid32[2]; const int8_t * q = (const int8_t *)grid32; - grid32[0] = iq1s_grid_gpu[x[i].qs[4*ib+il] | (((x[i].qh[ib] >> 3*il) & 7) << 8)]; - grid32[1] = (grid32[0] >> 4) & 0x0f0f0f0f; - grid32[0] &= 0x0f0f0f0f; - for (int j = 0; j < 8; ++j) { - y[j] = d * (q[j] + delta); - } -} - -template -static __global__ void dequantize_block_iq1_m(const void * __restrict__ vx, dst_t * __restrict__ yy) { - - const int64_t i = blockIdx.x; - const block_iq1_m * x = (const block_iq1_m *) vx; - - const int64_t tid = threadIdx.x; - const int64_t il = tid/8; // 0...3 - const int64_t ib = tid%8; // 0...7 - dst_t * y = yy + i*QK_K + 32*ib + 8*il; - const uint16_t * sc = (const uint16_t *)x[i].scales; - iq1m_scale_t scale; - scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000); - const int64_t ib16 = 2*ib + il/2; // sc[ib16/4] >> 3*(ib16%4) -> sc[ib/2] >> 3*((2*ib+il/2)%4); - const float d = __half2float(scale.f16) * (2*((sc[ib16/4] >> 3*(ib16%4)) & 0x7) + 1); - const float delta = x[i].qh[2*ib+il/2] & (0x08 << 4*(il%2)) ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA; - uint32_t grid32[2]; const int8_t * q = (const int8_t *)grid32; - grid32[0] = iq1s_grid_gpu[x[i].qs[4*ib+il] | (((x[i].qh[2*ib+il/2] >> 4*(il%2)) & 7) << 8)]; - grid32[1] = (grid32[0] >> 4) & 0x0f0f0f0f; - grid32[0] &= 0x0f0f0f0f; - for (int j = 0; j < 8; ++j) { - y[j] = d * (q[j] + delta); - } -} - -template -static __global__ void dequantize_block_iq4_nl(const void * __restrict__ vx, dst_t * __restrict__ yy) { - - const auto i = blockIdx.x; - const block_iq4_nl * x = (const block_iq4_nl *) vx + i*(QK_K/QK4_NL); - - const auto tid = threadIdx.x; - const int il = tid/8; // 0...3 - const int ib = tid%8; // 0...7 - dst_t * y = yy + i*QK_K + 32*ib + 4*il; - const uint8_t * q4 = x[ib].qs + 4*il; - const float d = __half2float(x[ib].d); - for (int j = 0; j < 4; ++j) { - y[j+ 0] = d * kvalues_iq4nl[q4[j] & 0xf]; - y[j+16] = d * kvalues_iq4nl[q4[j] >> 4]; - } - -} - -template -static __global__ void dequantize_block_iq4_xs(const void * __restrict__ vx, dst_t * __restrict__ yy) { - const auto i = blockIdx.x; - const block_iq4_xs * x = (const block_iq4_xs *)vx; - - const auto tid = threadIdx.x; - const int il = tid/8; // 0...3 - const int ib = tid%8; // 0...7 - dst_t * y = yy + i*QK_K + 32*ib + 4*il; - const uint8_t * q4 = x[i].qs + 16*ib + 4*il; - const float d = __half2float(x[i].d) * ((((x[i].scales_l[ib/2] >> 4*(ib%2)) & 0xf) | (((x[i].scales_h >> 2*ib) & 3) << 4)) - 32); - for (int j = 0; j < 4; ++j) { - y[j+ 0] = d * kvalues_iq4nl[q4[j] & 0xf]; - y[j+16] = d * kvalues_iq4nl[q4[j] >> 4]; - } -} - -template -static void dequantize_block_cuda(const void * __restrict__ vx, dst_t * __restrict__ y, const int64_t k, cudaStream_t stream) { - const int64_t num_blocks = (k + 2*CUDA_DEQUANTIZE_BLOCK_SIZE - 1) / (2*CUDA_DEQUANTIZE_BLOCK_SIZE); - dequantize_block<<>>(vx, y, k); -} - -template -static void dequantize_row_q2_K_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = k / QK_K; - dequantize_block_q2_K<<>>(vx, y); -} - -template -static void dequantize_row_q3_K_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = k / QK_K; - dequantize_block_q3_K<<>>(vx, y); -} - -template -static void dequantize_row_q4_K_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = k / QK_K; - dequantize_block_q4_K<<>>(vx, y); -} - -template -static void dequantize_row_q5_K_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = k / QK_K; - dequantize_block_q5_K<<>>(vx, y); -} - -template -static void dequantize_row_q6_K_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = k / QK_K; - dequantize_block_q6_K<<>>(vx, y); -} - -template -static void dequantize_row_iq2_xxs_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = k / QK_K; - dequantize_block_iq2_xxs<<>>(vx, y); -} - -template -static void dequantize_row_iq2_xs_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = k / QK_K; - dequantize_block_iq2_xs<<>>(vx, y); -} - -template -static void dequantize_row_iq2_s_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = k / QK_K; - dequantize_block_iq2_s<<>>(vx, y); -} - -template -static void dequantize_row_iq3_xxs_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = k / QK_K; - dequantize_block_iq3_xxs<<>>(vx, y); -} - -template -static void dequantize_row_iq3_s_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = k / QK_K; - dequantize_block_iq3_s<<>>(vx, y); -} - -template -static void dequantize_row_iq1_s_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = k / QK_K; - dequantize_block_iq1_s<<>>(vx, y); -} - -template -static void dequantize_row_iq1_m_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = k / QK_K; - dequantize_block_iq1_m<<>>(vx, y); -} - -template -static void dequantize_row_iq4_nl_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = (k + QK_K - 1) / QK_K; - dequantize_block_iq4_nl<<>>(vx, y); -} - -template -static void dequantize_row_iq4_xs_cuda(const void * vx, dst_t * y, const int64_t k, cudaStream_t stream) { - const int nb = (k + QK_K - 1) / QK_K; - dequantize_block_iq4_xs<<>>(vx, y); -} - -template -static to_cuda_ggml_t ggml_get_to_cuda(int64_t type) { - switch (type) { - case 2: - return dequantize_block_cuda; - case 3: - return dequantize_block_cuda; - case 6: - return dequantize_block_cuda; - case 7: - return dequantize_block_cuda; - case 8: - return dequantize_block_cuda; - case 10: - return dequantize_row_q2_K_cuda; - case 11: - return dequantize_row_q3_K_cuda; - case 12: - return dequantize_row_q4_K_cuda; - case 13: - return dequantize_row_q5_K_cuda; - case 14: - return dequantize_row_q6_K_cuda; - case 16: - return dequantize_row_iq2_xxs_cuda; - case 17: - return dequantize_row_iq2_xs_cuda; - case 18: - return dequantize_row_iq3_xxs_cuda; - case 19: - return dequantize_row_iq1_s_cuda; - case 20: - return dequantize_row_iq4_nl_cuda; - case 21: - return dequantize_row_iq3_s_cuda; - case 22: - return dequantize_row_iq2_s_cuda; - case 23: - return dequantize_row_iq4_xs_cuda; - case 29: - return dequantize_row_iq1_m_cuda; - default: - return nullptr; - } -} diff --git a/csrc/libtorch_stable/quantization/gguf/ggml-common.h b/csrc/libtorch_stable/quantization/gguf/ggml-common.h deleted file mode 100644 index 282875b8c73f..000000000000 --- a/csrc/libtorch_stable/quantization/gguf/ggml-common.h +++ /dev/null @@ -1,1150 +0,0 @@ -// copied from https://github.com/ggerganov/llama.cpp/blob/b2899/ggml-common.h -#define QK_K 256 -#define K_QUANTS_PER_ITERATION 2 -#define WARP_SIZE_GGUF 32 -#define K_SCALE_SIZE 12 -#define CUDA_DEQUANTIZE_BLOCK_SIZE 256 -#define CUDA_QUANTIZE_BLOCK_SIZE 256 -#define GGML_CUDA_DMMV_X 32 -#define GGML_CUDA_MMV_Y 1 - - -// Data Structures -// QK = number of values after dequantization -// QR = QK / number of values before dequantization -// QI = number of 32 bit integers before dequantization - -#define QK4_0 32 -#define QR4_0 2 -#define QI4_0 (QK4_0 / (4 * QR4_0)) -typedef struct { - half d; // delta - uint8_t qs[QK4_0 / 2]; // nibbles / quants -} block_q4_0; - -#define QK4_1 32 -#define QR4_1 2 -#define QI4_1 (QK4_1 / (4 * QR4_1)) -typedef struct { - half2 dm; // dm.x = delta, dm.y = min - uint8_t qs[QK4_1 / 2]; // nibbles / quants -} block_q4_1; - -#define QK5_0 32 -#define QR5_0 2 -#define QI5_0 (QK5_0 / (4 * QR5_0)) -typedef struct { - half d; // delta - uint8_t qh[4]; // 5-th bit of quants - uint8_t qs[QK5_0 / 2]; // nibbles / quants -} block_q5_0; - -#define QK5_1 32 -#define QR5_1 2 -#define QI5_1 (QK5_1 / (4 * QR5_1)) -typedef struct { - half2 dm; // dm.x = delta, dm.y = min - uint8_t qh[4]; // 5-th bit of quants - uint8_t qs[QK5_1 / 2]; // nibbles / quants -} block_q5_1; - -#define QK8_0 32 -#define QR8_0 1 -#define QI8_0 (QK8_0 / (4 * QR8_0)) -typedef struct { - half d; // delta - int8_t qs[QK8_0]; // quants -} block_q8_0; - -#define QK8_1 32 -#define QR8_1 1 -#define QI8_1 (QK8_1 / (4 * QR8_1)) -typedef struct { - half2 ds; // ds.x = delta, ds.y = sum - int8_t qs[QK8_0]; // quants -} block_q8_1; - -#define QR2_K 4 -#define QI2_K (QK_K / (4*QR2_K)) -typedef struct { - uint8_t scales[QK_K/16]; // scales and mins, quantized with 4 bits - uint8_t qs[QK_K/4]; // quants - half2 dm; // super-block scale for quantized scales/mins -} block_q2_K; - -#define QR3_K 4 -#define QI3_K (QK_K / (4*QR3_K)) -typedef struct { - uint8_t hmask[QK_K/8]; // quants - high bit - uint8_t qs[QK_K/4]; // quants - low 2 bits - uint8_t scales[K_SCALE_SIZE]; // scales, quantized with 6 bits - half d; // super-block scale -} block_q3_K; - -#define QR4_K 2 -#define QI4_K (QK_K / (4*QR4_K)) -typedef struct { - half2 dm; // super-block scale for quantized scales/mins - uint8_t scales[3*QK_K/64]; // scales, quantized with 6 bits - uint8_t qs[QK_K/2]; // 4--bit quants -} block_q4_K; - -#define QR5_K 2 -#define QI5_K (QK_K / (4*QR5_K)) -typedef struct { - half2 dm; // super-block scale for quantized scales/mins - uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits - uint8_t qh[QK_K/8]; // quants, high bit - uint8_t qs[QK_K/2]; // quants, low 4 bits -} block_q5_K; - -#define QR6_K 2 -#define QI6_K (QK_K / (4*QR6_K)) -typedef struct { - uint8_t ql[QK_K/2]; // quants, lower 4 bits - uint8_t qh[QK_K/4]; // quants, upper 2 bits - int8_t scales[QK_K/16]; // scales - half d; // delta -} block_q6_K; - -#define QR2_XXS 8 -#define QI2_XXS (QK_K / (4*QR2_XXS)) -typedef struct { - half d; - uint16_t qs[QK_K/8]; -} block_iq2_xxs; - -#define QR2_XS 8 -#define QI2_XS (QK_K / (4*QR2_XS)) -typedef struct { - half d; - uint16_t qs[QK_K/8]; - uint8_t scales[QK_K/32]; -} block_iq2_xs; - -#define QR2_S 8 -#define QI2_S (QK_K / (4*QR2_S)) -typedef struct { - half d; - uint8_t qs[QK_K/4]; - uint8_t qh[QK_K/32]; - uint8_t scales[QK_K/32]; -} block_iq2_s; - -#define QR3_XXS 8 -#define QI3_XXS (QK_K / (4*QR3_XXS)) -typedef struct { - half d; - uint8_t qs[3*(QK_K/8)]; -} block_iq3_xxs; - -#define QR3_XS 8 -#define QI3_XS (QK_K / (4*QR3_XS)) -#define IQ3S_N_SCALE QK_K/64 -typedef struct { - half d; - uint8_t qs[QK_K/4]; - uint8_t qh[QK_K/32]; - uint8_t signs[QK_K/8]; - uint8_t scales[IQ3S_N_SCALE]; -} block_iq3_s; - -// 1.5625 bpw -#define QR1_S 8 -#define QI1_S (QK_K / (4*QR1_S)) -typedef struct { - half d; - uint8_t qs[QK_K/8]; - uint16_t qh[QK_K/32]; -} block_iq1_s; - -// 1.75 bpw -#define QR1_M 8 -#define QI1_M (QK_K / (4*QR1_M)) -typedef struct { - uint8_t qs[QK_K/8]; // grid index, low 8 bits - uint8_t qh[QK_K/16]; // grid index, high 3 bits + grid shift bit (for two groups of 8) - uint8_t scales[QK_K/32]; // 3-bit block scales (4-bit if QK_K == 64) -} block_iq1_m; - -// Used by IQ1_M quants -typedef union { - half f16; - uint16_t u16; -} iq1m_scale_t; - -#define QK4_NL 32 -#define QR4_NL 2 -#define QI4_NL (QK4_NL / (4*QR4_NL)) -typedef struct { - half d; - uint8_t qs[QK4_NL/2]; -} block_iq4_nl; - -#define QR4_XS 8 -#define QI4_XS (QK_K / (4*QR4_XS)) -typedef struct { - half d; - uint16_t scales_h; - uint8_t scales_l[QK_K/64]; - uint8_t qs[QK_K/2]; -} block_iq4_xs; - -static const __device__ uint64_t iq2xxs_grid[256] = { - 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, - 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x08080808082b0808, - 0x08080808082b082b, 0x08080808082b2b08, 0x08080808082b2b2b, 0x0808080819080819, - 0x0808080819081908, 0x0808080819190808, 0x0808080819192b08, 0x08080808192b0819, - 0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b, 0x080808082b082b2b, - 0x080808082b2b082b, 0x0808081908080819, 0x0808081908081908, 0x0808081908190808, - 0x0808081908191919, 0x0808081919080808, 0x080808192b081908, 0x080808192b192b08, - 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b082b082b, 0x0808082b2b08082b, - 0x0808190808080819, 0x0808190808081908, 0x0808190808190808, 0x08081908082b0819, - 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819082b08, - 0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, - 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908082b08, - 0x08081919082b0808, 0x080819191908192b, 0x08081919192b2b19, 0x080819192b080808, - 0x080819192b190819, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b19080808, - 0x0808192b2b081908, 0x0808192b2b2b1908, 0x08082b0808080808, 0x08082b0808081919, - 0x08082b0808082b08, 0x08082b0808191908, 0x08082b08082b2b08, 0x08082b0819080819, - 0x08082b0819081908, 0x08082b0819190808, 0x08082b081919082b, 0x08082b082b082b08, - 0x08082b1908081908, 0x08082b1919080808, 0x08082b2b0808082b, 0x08082b2b08191908, - 0x0819080808080819, 0x0819080808081908, 0x0819080808190808, 0x08190808082b0819, - 0x0819080819080808, 0x08190808192b0808, 0x081908082b081908, 0x081908082b190808, - 0x081908082b191919, 0x0819081908080808, 0x0819081908082b08, 0x08190819082b0808, - 0x0819081919190808, 0x0819081919192b2b, 0x081908192b080808, 0x0819082b082b1908, - 0x0819082b19081919, 0x0819190808080808, 0x0819190808082b08, 0x08191908082b0808, - 0x08191908082b1919, 0x0819190819082b19, 0x081919082b080808, 0x0819191908192b08, - 0x08191919192b082b, 0x0819192b08080808, 0x0819192b0819192b, 0x08192b0808080819, - 0x08192b0808081908, 0x08192b0808190808, 0x08192b0819080808, 0x08192b082b080819, - 0x08192b1908080808, 0x08192b1908081919, 0x08192b192b2b0808, 0x08192b2b19190819, - 0x082b080808080808, 0x082b08080808082b, 0x082b080808082b2b, 0x082b080819081908, - 0x082b0808192b0819, 0x082b08082b080808, 0x082b08082b08082b, 0x082b0819082b2b19, - 0x082b081919082b08, 0x082b082b08080808, 0x082b082b0808082b, 0x082b190808080819, - 0x082b190808081908, 0x082b190808190808, 0x082b190819080808, 0x082b19081919192b, - 0x082b191908080808, 0x082b191919080819, 0x082b1919192b1908, 0x082b192b2b190808, - 0x082b2b0808082b08, 0x082b2b08082b0808, 0x082b2b082b191908, 0x082b2b2b19081908, - 0x1908080808080819, 0x1908080808081908, 0x1908080808190808, 0x1908080808192b08, - 0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808, 0x1908080819082b08, - 0x190808081919192b, 0x19080808192b0808, 0x190808082b080819, 0x190808082b081908, - 0x190808082b190808, 0x1908081908080808, 0x19080819082b0808, 0x19080819192b0819, - 0x190808192b080808, 0x190808192b081919, 0x1908082b08080819, 0x1908082b08190808, - 0x1908082b19082b08, 0x1908082b1919192b, 0x1908082b192b2b08, 0x1908190808080808, - 0x1908190808082b08, 0x19081908082b0808, 0x190819082b080808, 0x190819082b192b19, - 0x190819190819082b, 0x19081919082b1908, 0x1908192b08080808, 0x19082b0808080819, - 0x19082b0808081908, 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, - 0x19082b1908080808, 0x19082b1919192b08, 0x19082b19192b0819, 0x19082b192b08082b, - 0x19082b2b19081919, 0x19082b2b2b190808, 0x1919080808080808, 0x1919080808082b08, - 0x1919080808190819, 0x1919080808192b19, 0x19190808082b0808, 0x191908082b080808, - 0x191908082b082b08, 0x1919081908081908, 0x191908191908082b, 0x191908192b2b1908, - 0x1919082b2b190819, 0x191919082b190808, 0x191919082b19082b, 0x1919191908082b2b, - 0x1919192b08080819, 0x1919192b19191908, 0x19192b0808080808, 0x19192b0808190819, - 0x19192b0808192b19, 0x19192b08192b1908, 0x19192b1919080808, 0x19192b2b08082b08, - 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b0808192b2b08, - 0x192b081908080808, 0x192b081919191919, 0x192b082b08192b08, 0x192b082b192b0808, - 0x192b190808080808, 0x192b190808081919, 0x192b191908190808, 0x192b19190819082b, - 0x192b19192b081908, 0x192b2b081908082b, 0x2b08080808080808, 0x2b0808080808082b, - 0x2b08080808082b2b, 0x2b08080819080819, 0x2b0808082b08082b, 0x2b08081908081908, - 0x2b08081908192b08, 0x2b08081919080808, 0x2b08082b08190819, 0x2b08190808080819, - 0x2b08190808081908, 0x2b08190808190808, 0x2b08190808191919, 0x2b08190819080808, - 0x2b081908192b0808, 0x2b08191908080808, 0x2b0819191908192b, 0x2b0819192b191908, - 0x2b08192b08082b19, 0x2b08192b19080808, 0x2b08192b192b0808, 0x2b082b080808082b, - 0x2b082b1908081908, 0x2b082b2b08190819, 0x2b19080808081908, 0x2b19080808190808, - 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908082b2b0819, 0x2b1908190819192b, - 0x2b1908192b080808, 0x2b19082b19081919, 0x2b19190808080808, 0x2b191908082b082b, - 0x2b19190819081908, 0x2b19191919190819, 0x2b192b082b080819, 0x2b192b19082b0808, - 0x2b2b08080808082b, 0x2b2b080819190808, 0x2b2b08082b081919, 0x2b2b081908082b19, - 0x2b2b082b08080808, 0x2b2b190808192b08, 0x2b2b2b0819190808, 0x2b2b2b1908081908, -}; - -static const __device__ uint64_t iq2xs_grid[512] = { - 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, - 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, - 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, - 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, - 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, - 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x080808082b080808, - 0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819, - 0x080808082b191908, 0x080808082b192b19, 0x080808082b2b0808, 0x0808081908080819, - 0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, - 0x080808190819082b, 0x0808081908191919, 0x0808081908192b08, 0x0808081908192b2b, - 0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b, - 0x0808081919081919, 0x0808081919082b08, 0x0808081919190819, 0x0808081919191908, - 0x08080819192b0808, 0x08080819192b2b08, 0x080808192b080819, 0x080808192b081908, - 0x080808192b190808, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b08081919, - 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808, - 0x0808082b19080819, 0x0808082b19081908, 0x0808082b19190808, 0x0808082b19191919, - 0x0808082b2b080808, 0x0808082b2b082b2b, 0x0808190808080819, 0x0808190808081908, - 0x080819080808192b, 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, - 0x0808190808191919, 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, - 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, 0x0808190819082b08, - 0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x08081908192b0808, - 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x0808191908080808, - 0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908190819, - 0x0808191908191908, 0x08081919082b0808, 0x0808191919080819, 0x0808191919081908, - 0x0808191919190808, 0x08081919192b0819, 0x080819192b080808, 0x0808192b08080819, - 0x0808192b08081908, 0x0808192b08190808, 0x0808192b082b192b, 0x0808192b19080808, - 0x0808192b1908082b, 0x0808192b2b081908, 0x08082b0808080808, 0x08082b080808082b, - 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808082b2b, 0x08082b0808190819, - 0x08082b0808191908, 0x08082b08082b0808, 0x08082b08082b1919, 0x08082b0819080819, - 0x08082b0819081908, 0x08082b0819190808, 0x08082b0819192b08, 0x08082b082b080808, - 0x08082b082b2b0808, 0x08082b082b2b2b2b, 0x08082b1908080819, 0x08082b1908081908, - 0x08082b1908190808, 0x08082b1919080808, 0x08082b192b080819, 0x08082b192b082b19, - 0x08082b2b08080808, 0x08082b2b082b0808, 0x08082b2b082b2b08, 0x08082b2b2b19192b, - 0x08082b2b2b2b0808, 0x0819080808080819, 0x0819080808081908, 0x081908080808192b, - 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919, - 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, 0x0819080819080808, - 0x081908081908082b, 0x0819080819081919, 0x0819080819082b08, 0x0819080819190819, - 0x0819080819191908, 0x08190808192b0808, 0x08190808192b2b2b, 0x081908082b080819, - 0x081908082b081908, 0x081908082b190808, 0x0819081908080808, 0x081908190808082b, - 0x0819081908081919, 0x0819081908082b08, 0x0819081908190819, 0x0819081908191908, - 0x08190819082b0808, 0x0819081919080819, 0x0819081919081908, 0x0819081919190808, - 0x081908192b080808, 0x081908192b191908, 0x081908192b19192b, 0x0819082b08080819, - 0x0819082b08081908, 0x0819082b0808192b, 0x0819082b08190808, 0x0819082b19080808, - 0x0819082b192b0808, 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, - 0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x08191908082b0808, - 0x0819190819080819, 0x0819190819081908, 0x0819190819082b19, 0x0819190819190808, - 0x08191908192b1908, 0x081919082b080808, 0x0819191908080819, 0x0819191908081908, - 0x0819191908190808, 0x0819191919080808, 0x0819192b08080808, 0x0819192b08191908, - 0x0819192b19082b19, 0x08192b0808080819, 0x08192b0808081908, 0x08192b0808190808, - 0x08192b080819082b, 0x08192b0819080808, 0x08192b0819191908, 0x08192b082b08192b, - 0x08192b1908080808, 0x08192b1908081919, 0x08192b19192b192b, 0x08192b2b19190819, - 0x08192b2b2b2b2b19, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, - 0x082b080808082b08, 0x082b080808082b2b, 0x082b080808190819, 0x082b080808191908, - 0x082b0808082b0808, 0x082b080819080819, 0x082b080819081908, 0x082b080819190808, - 0x082b08082b080808, 0x082b08082b2b0808, 0x082b081908080819, 0x082b081908081908, - 0x082b081908190808, 0x082b081919080808, 0x082b081919082b08, 0x082b0819192b1919, - 0x082b082b08080808, 0x082b082b082b082b, 0x082b082b2b080808, 0x082b082b2b2b2b08, - 0x082b190808080819, 0x082b190808081908, 0x082b190808190808, 0x082b1908082b2b19, - 0x082b190819080808, 0x082b191908080808, 0x082b191919080819, 0x082b19191919082b, - 0x082b19192b192b19, 0x082b192b08080819, 0x082b192b08192b2b, 0x082b192b2b2b192b, - 0x082b2b0808080808, 0x082b2b0808082b08, 0x082b2b0808082b2b, 0x082b2b08082b0808, - 0x082b2b0819191919, 0x082b2b082b082b08, 0x082b2b082b2b082b, 0x082b2b19192b2b08, - 0x082b2b192b190808, 0x082b2b2b08082b08, 0x082b2b2b082b0808, 0x082b2b2b2b08082b, - 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, 0x1908080808081908, - 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b, - 0x1908080808191919, 0x1908080808192b08, 0x19080808082b0819, 0x19080808082b1908, - 0x1908080819080808, 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, - 0x1908080819082b2b, 0x1908080819190819, 0x1908080819191908, 0x19080808192b0808, - 0x19080808192b1919, 0x190808082b080819, 0x190808082b081908, 0x190808082b190808, - 0x1908081908080808, 0x190808190808082b, 0x1908081908081919, 0x1908081908082b08, - 0x1908081908190819, 0x1908081908191908, 0x19080819082b0808, 0x1908081919080819, - 0x1908081919081908, 0x1908081919190808, 0x190808192b080808, 0x190808192b081919, - 0x190808192b2b082b, 0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808, - 0x1908082b0819082b, 0x1908082b082b2b19, 0x1908082b19080808, 0x1908190808080808, - 0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808190819, - 0x1908190808191908, 0x1908190808192b19, 0x19081908082b0808, 0x1908190819080819, - 0x1908190819081908, 0x1908190819190808, 0x190819082b080808, 0x190819082b191908, - 0x1908191908080819, 0x1908191908081908, 0x1908191908190808, 0x19081919082b1908, - 0x1908191919080808, 0x190819192b192b2b, 0x1908192b08080808, 0x1908192b08082b2b, - 0x1908192b19081908, 0x1908192b19190808, 0x19082b0808080819, 0x19082b0808081908, - 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, 0x19082b0819191908, - 0x19082b08192b082b, 0x19082b1908080808, 0x19082b1908190819, 0x19082b1919081908, - 0x19082b1919190808, 0x19082b19192b2b19, 0x19082b2b08081908, 0x1919080808080808, - 0x191908080808082b, 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, - 0x1919080808191908, 0x19190808082b0808, 0x19190808082b2b08, 0x1919080819080819, - 0x1919080819081908, 0x1919080819190808, 0x191908082b080808, 0x1919081908080819, - 0x1919081908081908, 0x1919081908190808, 0x1919081908191919, 0x1919081919080808, - 0x191908191908082b, 0x1919082b08080808, 0x1919082b19081908, 0x1919082b2b2b2b2b, - 0x1919190808080819, 0x1919190808081908, 0x1919190808190808, 0x19191908082b0819, - 0x1919190819080808, 0x19191908192b0808, 0x191919082b080819, 0x191919082b2b0819, - 0x1919191908080808, 0x1919191908082b08, 0x191919192b080808, 0x191919192b082b08, - 0x1919192b082b0819, 0x1919192b192b2b08, 0x1919192b2b2b0819, 0x19192b0808080808, - 0x19192b0808191908, 0x19192b0819080819, 0x19192b0819190808, 0x19192b082b192b19, - 0x19192b1908192b2b, 0x19192b1919080808, 0x19192b191908082b, 0x19192b2b2b081919, - 0x192b080808080819, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, - 0x192b080819191908, 0x192b0808192b082b, 0x192b08082b08192b, 0x192b08082b2b2b19, - 0x192b081908080808, 0x192b082b082b1908, 0x192b082b19082b2b, 0x192b082b2b19082b, - 0x192b190808080808, 0x192b19080819192b, 0x192b191908190808, 0x192b191919080808, - 0x192b191919081919, 0x192b19192b2b1908, 0x192b2b0808080819, 0x192b2b08192b2b2b, - 0x192b2b19082b1919, 0x192b2b2b0808192b, 0x192b2b2b19191908, 0x192b2b2b192b082b, - 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, - 0x2b08080808190819, 0x2b08080808191908, 0x2b080808082b0808, 0x2b080808082b2b2b, - 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808082b080808, - 0x2b0808082b08082b, 0x2b0808082b2b2b08, 0x2b0808082b2b2b2b, 0x2b08081908080819, - 0x2b08081908081908, 0x2b0808190808192b, 0x2b08081908190808, 0x2b08081919080808, - 0x2b08081919190819, 0x2b08081919192b19, 0x2b08082b08080808, 0x2b08082b082b0808, - 0x2b08082b2b080808, 0x2b08082b2b08082b, 0x2b08082b2b2b0808, 0x2b08082b2b2b2b08, - 0x2b08190808080819, 0x2b08190808081908, 0x2b08190808190808, 0x2b0819080819082b, - 0x2b08190808191919, 0x2b08190819080808, 0x2b081908192b0808, 0x2b0819082b082b19, - 0x2b08191908080808, 0x2b08191919081908, 0x2b0819192b2b1919, 0x2b08192b08192b08, - 0x2b08192b192b2b2b, 0x2b082b0808080808, 0x2b082b0808082b08, 0x2b082b08082b1919, - 0x2b082b0819192b2b, 0x2b082b082b080808, 0x2b082b082b08082b, 0x2b082b082b2b2b08, - 0x2b082b190808192b, 0x2b082b2b082b082b, 0x2b082b2b2b080808, 0x2b082b2b2b082b08, - 0x2b082b2b2b19192b, 0x2b082b2b2b2b2b08, 0x2b19080808080819, 0x2b19080808081908, - 0x2b19080808190808, 0x2b19080819080808, 0x2b1908081919192b, 0x2b1908082b081908, - 0x2b19081908080808, 0x2b190819082b082b, 0x2b190819192b1908, 0x2b19082b1919192b, - 0x2b19082b2b082b19, 0x2b19190808080808, 0x2b19190808081919, 0x2b19190819081908, - 0x2b19190819190808, 0x2b19190819192b08, 0x2b191919082b2b19, 0x2b1919192b190808, - 0x2b1919192b19082b, 0x2b19192b19080819, 0x2b192b0819190819, 0x2b192b082b2b192b, - 0x2b192b1919082b19, 0x2b192b2b08191919, 0x2b192b2b192b0808, 0x2b2b080808080808, - 0x2b2b08080808082b, 0x2b2b080808082b08, 0x2b2b080808082b2b, 0x2b2b0808082b0808, - 0x2b2b0808082b2b2b, 0x2b2b08082b2b0808, 0x2b2b081919190819, 0x2b2b081919192b19, - 0x2b2b08192b2b192b, 0x2b2b082b08080808, 0x2b2b082b0808082b, 0x2b2b082b08082b08, - 0x2b2b082b082b2b2b, 0x2b2b082b2b080808, 0x2b2b082b2b2b0808, 0x2b2b190819080808, - 0x2b2b19082b191919, 0x2b2b192b192b1919, 0x2b2b192b2b192b08, 0x2b2b2b0808082b2b, - 0x2b2b2b08082b0808, 0x2b2b2b08082b082b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b0808, - 0x2b2b2b082b2b2b08, 0x2b2b2b1908081908, 0x2b2b2b192b081908, 0x2b2b2b192b08192b, - 0x2b2b2b2b082b2b08, 0x2b2b2b2b082b2b2b, 0x2b2b2b2b2b190819, 0x2b2b2b2b2b2b2b2b, -}; - -static const __device__ uint64_t iq2s_grid[1024] = { - 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, - 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, - 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, - 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, - 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, - 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x08080808192b192b, - 0x08080808192b2b19, 0x080808082b080808, 0x080808082b08082b, 0x080808082b081919, - 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b2b0808, - 0x080808082b2b1919, 0x080808082b2b2b2b, 0x0808081908080819, 0x0808081908081908, - 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b, - 0x0808081908191919, 0x0808081908192b08, 0x08080819082b0819, 0x08080819082b1908, - 0x0808081919080808, 0x080808191908082b, 0x0808081919081919, 0x0808081919082b08, - 0x0808081919190819, 0x0808081919191908, 0x080808191919192b, 0x0808081919192b19, - 0x08080819192b0808, 0x08080819192b1919, 0x08080819192b2b08, 0x080808192b080819, - 0x080808192b081908, 0x080808192b190808, 0x080808192b19082b, 0x080808192b191919, - 0x080808192b2b0819, 0x080808192b2b1908, 0x0808082b08080808, 0x0808082b0808082b, - 0x0808082b08081919, 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, - 0x0808082b082b0808, 0x0808082b082b2b2b, 0x0808082b19080819, 0x0808082b19081908, - 0x0808082b1908192b, 0x0808082b19082b19, 0x0808082b19190808, 0x0808082b19191919, - 0x0808082b2b080808, 0x0808082b2b081919, 0x0808082b2b082b2b, 0x0808082b2b191908, - 0x0808082b2b2b082b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, - 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, 0x0808190808191919, - 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, 0x08081908082b192b, - 0x08081908082b2b19, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, - 0x0808190819082b08, 0x0808190819082b2b, 0x0808190819190819, 0x0808190819191908, - 0x080819081919192b, 0x0808190819192b19, 0x08081908192b0808, 0x08081908192b082b, - 0x08081908192b1919, 0x080819082b080819, 0x080819082b081908, 0x080819082b08192b, - 0x080819082b082b19, 0x080819082b190808, 0x080819082b191919, 0x080819082b192b08, - 0x080819082b2b0819, 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, - 0x0808191908081919, 0x0808191908082b08, 0x0808191908082b2b, 0x0808191908190819, - 0x0808191908191908, 0x080819190819192b, 0x0808191908192b19, 0x08081919082b0808, - 0x08081919082b1919, 0x08081919082b2b08, 0x0808191919080819, 0x0808191919081908, - 0x080819191908192b, 0x0808191919082b19, 0x0808191919190808, 0x080819191919082b, - 0x0808191919191919, 0x0808191919192b08, 0x08081919192b0819, 0x08081919192b1908, - 0x080819192b080808, 0x080819192b08082b, 0x080819192b081919, 0x080819192b082b08, - 0x080819192b190819, 0x080819192b191908, 0x080819192b2b0808, 0x0808192b08080819, - 0x0808192b08081908, 0x0808192b0808192b, 0x0808192b08082b19, 0x0808192b08190808, - 0x0808192b08191919, 0x0808192b19080808, 0x0808192b19081919, 0x0808192b19082b08, - 0x0808192b19190819, 0x0808192b19191908, 0x0808192b192b0808, 0x0808192b2b080819, - 0x0808192b2b081908, 0x0808192b2b190808, 0x08082b0808080808, 0x08082b080808082b, - 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808190819, 0x08082b0808191908, - 0x08082b080819192b, 0x08082b0808192b19, 0x08082b08082b0808, 0x08082b08082b1919, - 0x08082b08082b2b2b, 0x08082b0819080819, 0x08082b0819081908, 0x08082b081908192b, - 0x08082b0819082b19, 0x08082b0819190808, 0x08082b081919082b, 0x08082b0819191919, - 0x08082b0819192b08, 0x08082b08192b0819, 0x08082b08192b1908, 0x08082b082b080808, - 0x08082b082b081919, 0x08082b082b191908, 0x08082b082b2b2b2b, 0x08082b1908080819, - 0x08082b1908081908, 0x08082b1908190808, 0x08082b190819082b, 0x08082b1908191919, - 0x08082b1908192b08, 0x08082b19082b0819, 0x08082b1919080808, 0x08082b1919081919, - 0x08082b1919082b08, 0x08082b1919190819, 0x08082b1919191908, 0x08082b19192b0808, - 0x08082b192b080819, 0x08082b192b190808, 0x08082b2b08080808, 0x08082b2b08190819, - 0x08082b2b08191908, 0x08082b2b082b082b, 0x08082b2b082b2b08, 0x08082b2b082b2b2b, - 0x08082b2b19190808, 0x08082b2b2b192b19, 0x0819080808080819, 0x0819080808081908, - 0x081908080808192b, 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, - 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, - 0x08190808082b192b, 0x0819080819080808, 0x081908081908082b, 0x0819080819081919, - 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x081908081919192b, - 0x0819080819192b19, 0x08190808192b0808, 0x08190808192b082b, 0x08190808192b1919, - 0x08190808192b2b08, 0x081908082b080819, 0x081908082b081908, 0x081908082b08192b, - 0x081908082b190808, 0x081908082b191919, 0x081908082b192b08, 0x081908082b2b0819, - 0x081908082b2b1908, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919, - 0x0819081908082b08, 0x0819081908082b2b, 0x0819081908190819, 0x0819081908191908, - 0x081908190819192b, 0x0819081908192b19, 0x08190819082b0808, 0x08190819082b082b, - 0x08190819082b1919, 0x08190819082b2b08, 0x0819081919080819, 0x0819081919081908, - 0x081908191908192b, 0x0819081919082b19, 0x0819081919190808, 0x081908191919082b, - 0x0819081919191919, 0x0819081919192b08, 0x08190819192b0819, 0x08190819192b1908, - 0x081908192b080808, 0x081908192b08082b, 0x081908192b081919, 0x081908192b082b08, - 0x081908192b190819, 0x081908192b191908, 0x0819082b08080819, 0x0819082b08081908, - 0x0819082b08082b19, 0x0819082b08190808, 0x0819082b08191919, 0x0819082b082b0819, - 0x0819082b082b1908, 0x0819082b19080808, 0x0819082b19081919, 0x0819082b19190819, - 0x0819082b19191908, 0x0819082b2b080819, 0x0819082b2b081908, 0x0819082b2b190808, - 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, 0x0819190808082b08, - 0x0819190808190819, 0x0819190808191908, 0x081919080819192b, 0x0819190808192b19, - 0x08191908082b0808, 0x08191908082b1919, 0x08191908082b2b08, 0x0819190819080819, - 0x0819190819081908, 0x081919081908192b, 0x0819190819082b19, 0x0819190819190808, - 0x081919081919082b, 0x0819190819191919, 0x0819190819192b08, 0x08191908192b0819, - 0x08191908192b1908, 0x081919082b080808, 0x081919082b08082b, 0x081919082b081919, - 0x081919082b082b08, 0x081919082b190819, 0x081919082b191908, 0x081919082b2b0808, - 0x0819191908080819, 0x0819191908081908, 0x081919190808192b, 0x0819191908082b19, - 0x0819191908190808, 0x081919190819082b, 0x0819191908191919, 0x0819191908192b08, - 0x08191919082b0819, 0x08191919082b1908, 0x0819191919080808, 0x081919191908082b, - 0x0819191919081919, 0x0819191919082b08, 0x0819191919190819, 0x0819191919191908, - 0x08191919192b0808, 0x081919192b080819, 0x081919192b081908, 0x081919192b190808, - 0x0819192b08080808, 0x0819192b08081919, 0x0819192b08082b08, 0x0819192b08190819, - 0x0819192b08191908, 0x0819192b082b0808, 0x0819192b19080819, 0x0819192b19081908, - 0x0819192b19190808, 0x0819192b2b080808, 0x0819192b2b2b2b2b, 0x08192b0808080819, - 0x08192b0808081908, 0x08192b080808192b, 0x08192b0808082b19, 0x08192b0808190808, - 0x08192b0808191919, 0x08192b0808192b08, 0x08192b08082b0819, 0x08192b0819080808, - 0x08192b081908082b, 0x08192b0819081919, 0x08192b0819082b08, 0x08192b0819190819, - 0x08192b0819191908, 0x08192b08192b0808, 0x08192b082b080819, 0x08192b082b081908, - 0x08192b1908080808, 0x08192b190808082b, 0x08192b1908081919, 0x08192b1908082b08, - 0x08192b1908190819, 0x08192b1908191908, 0x08192b19082b0808, 0x08192b1919080819, - 0x08192b1919081908, 0x08192b1919190808, 0x08192b19192b2b19, 0x08192b192b2b082b, - 0x08192b2b08081908, 0x08192b2b08190808, 0x08192b2b19080808, 0x08192b2b1919192b, - 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, 0x082b080808082b08, - 0x082b080808190819, 0x082b080808191908, 0x082b08080819192b, 0x082b080808192b19, - 0x082b0808082b0808, 0x082b0808082b1919, 0x082b0808082b2b2b, 0x082b080819080819, - 0x082b080819081908, 0x082b080819190808, 0x082b08081919082b, 0x082b080819191919, - 0x082b0808192b1908, 0x082b08082b080808, 0x082b08082b082b2b, 0x082b08082b191908, - 0x082b08082b2b2b2b, 0x082b081908080819, 0x082b081908081908, 0x082b081908190808, - 0x082b08190819082b, 0x082b081908191919, 0x082b0819082b0819, 0x082b081919080808, - 0x082b08191908082b, 0x082b081919081919, 0x082b081919190819, 0x082b081919191908, - 0x082b0819192b0808, 0x082b08192b080819, 0x082b08192b081908, 0x082b08192b190808, - 0x082b082b08080808, 0x082b082b08082b2b, 0x082b082b082b082b, 0x082b082b082b2b08, - 0x082b082b082b2b2b, 0x082b082b19081908, 0x082b082b19190808, 0x082b082b2b082b08, - 0x082b082b2b082b2b, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908, - 0x082b19080808192b, 0x082b190808082b19, 0x082b190808190808, 0x082b190808191919, - 0x082b190808192b08, 0x082b1908082b0819, 0x082b1908082b1908, 0x082b190819080808, - 0x082b19081908082b, 0x082b190819081919, 0x082b190819082b08, 0x082b190819190819, - 0x082b190819191908, 0x082b1908192b0808, 0x082b19082b080819, 0x082b19082b081908, - 0x082b19082b190808, 0x082b191908080808, 0x082b191908081919, 0x082b191908082b08, - 0x082b191908190819, 0x082b191908191908, 0x082b1919082b0808, 0x082b191919080819, - 0x082b191919081908, 0x082b191919190808, 0x082b1919192b192b, 0x082b19192b080808, - 0x082b192b08080819, 0x082b192b08081908, 0x082b192b08190808, 0x082b192b19080808, - 0x082b192b19192b19, 0x082b2b0808080808, 0x082b2b0808081919, 0x082b2b0808190819, - 0x082b2b0808191908, 0x082b2b0819080819, 0x082b2b0819081908, 0x082b2b0819190808, - 0x082b2b082b082b2b, 0x082b2b082b2b2b2b, 0x082b2b1908080819, 0x082b2b1908081908, - 0x082b2b1908190808, 0x082b2b192b191919, 0x082b2b2b08082b2b, 0x082b2b2b082b082b, - 0x082b2b2b192b1908, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, - 0x1908080808081908, 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, - 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x1908080808192b2b, - 0x19080808082b0819, 0x19080808082b1908, 0x19080808082b192b, 0x1908080819080808, - 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b, - 0x1908080819190819, 0x1908080819191908, 0x190808081919192b, 0x1908080819192b19, - 0x19080808192b0808, 0x19080808192b082b, 0x19080808192b1919, 0x190808082b080819, - 0x190808082b081908, 0x190808082b190808, 0x190808082b191919, 0x190808082b192b08, - 0x190808082b2b0819, 0x190808082b2b1908, 0x1908081908080808, 0x190808190808082b, - 0x1908081908081919, 0x1908081908082b08, 0x1908081908190819, 0x1908081908191908, - 0x190808190819192b, 0x1908081908192b19, 0x19080819082b0808, 0x19080819082b082b, - 0x19080819082b1919, 0x1908081919080819, 0x1908081919081908, 0x190808191908192b, - 0x1908081919082b19, 0x1908081919190808, 0x190808191919082b, 0x1908081919191919, - 0x1908081919192b08, 0x19080819192b0819, 0x19080819192b1908, 0x190808192b080808, - 0x190808192b08082b, 0x190808192b081919, 0x190808192b082b08, 0x190808192b190819, - 0x190808192b191908, 0x190808192b2b0808, 0x1908082b08080819, 0x1908082b08081908, - 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b08191919, 0x1908082b08192b08, - 0x1908082b082b1908, 0x1908082b19080808, 0x1908082b19081919, 0x1908082b19082b08, - 0x1908082b19190819, 0x1908082b19191908, 0x1908082b192b0808, 0x1908082b2b080819, - 0x1908082b2b081908, 0x1908190808080808, 0x190819080808082b, 0x1908190808081919, - 0x1908190808082b08, 0x1908190808082b2b, 0x1908190808190819, 0x1908190808191908, - 0x190819080819192b, 0x1908190808192b19, 0x19081908082b0808, 0x19081908082b082b, - 0x19081908082b1919, 0x19081908082b2b08, 0x1908190819080819, 0x1908190819081908, - 0x190819081908192b, 0x1908190819082b19, 0x1908190819190808, 0x190819081919082b, - 0x1908190819191919, 0x1908190819192b08, 0x19081908192b0819, 0x19081908192b1908, - 0x190819082b080808, 0x190819082b08082b, 0x190819082b081919, 0x190819082b082b08, - 0x190819082b190819, 0x190819082b191908, 0x190819082b2b0808, 0x1908191908080819, - 0x1908191908081908, 0x190819190808192b, 0x1908191908082b19, 0x1908191908190808, - 0x190819190819082b, 0x1908191908191919, 0x1908191908192b08, 0x19081919082b0819, - 0x19081919082b1908, 0x1908191919080808, 0x190819191908082b, 0x1908191919081919, - 0x1908191919082b08, 0x1908191919190819, 0x1908191919191908, 0x19081919192b0808, - 0x19081919192b2b2b, 0x190819192b080819, 0x190819192b081908, 0x190819192b190808, - 0x1908192b08080808, 0x1908192b0808082b, 0x1908192b08081919, 0x1908192b08082b08, - 0x1908192b08190819, 0x1908192b08191908, 0x1908192b082b0808, 0x1908192b19080819, - 0x1908192b19081908, 0x1908192b19190808, 0x1908192b2b080808, 0x1908192b2b2b1919, - 0x19082b0808080819, 0x19082b0808081908, 0x19082b0808082b19, 0x19082b0808190808, - 0x19082b080819082b, 0x19082b0808191919, 0x19082b0808192b08, 0x19082b08082b0819, - 0x19082b08082b1908, 0x19082b0819080808, 0x19082b081908082b, 0x19082b0819081919, - 0x19082b0819082b08, 0x19082b0819190819, 0x19082b0819191908, 0x19082b08192b0808, - 0x19082b082b081908, 0x19082b082b190808, 0x19082b1908080808, 0x19082b190808082b, - 0x19082b1908081919, 0x19082b1908082b08, 0x19082b1908190819, 0x19082b1908191908, - 0x19082b19082b0808, 0x19082b1919080819, 0x19082b1919081908, 0x19082b1919190808, - 0x19082b192b080808, 0x19082b192b19192b, 0x19082b2b08080819, 0x19082b2b08081908, - 0x19082b2b08190808, 0x19082b2b19080808, 0x1919080808080808, 0x191908080808082b, - 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, 0x1919080808191908, - 0x191908080819192b, 0x1919080808192b19, 0x19190808082b0808, 0x19190808082b082b, - 0x19190808082b1919, 0x19190808082b2b08, 0x1919080819080819, 0x1919080819081908, - 0x191908081908192b, 0x1919080819082b19, 0x1919080819190808, 0x191908081919082b, - 0x1919080819191919, 0x1919080819192b08, 0x19190808192b0819, 0x19190808192b1908, - 0x191908082b080808, 0x191908082b08082b, 0x191908082b081919, 0x191908082b082b08, - 0x191908082b190819, 0x191908082b191908, 0x1919081908080819, 0x1919081908081908, - 0x191908190808192b, 0x1919081908082b19, 0x1919081908190808, 0x191908190819082b, - 0x1919081908191919, 0x1919081908192b08, 0x19190819082b0819, 0x19190819082b1908, - 0x1919081919080808, 0x191908191908082b, 0x1919081919081919, 0x1919081919082b08, - 0x1919081919190819, 0x1919081919191908, 0x19190819192b0808, 0x191908192b080819, - 0x191908192b081908, 0x191908192b190808, 0x1919082b08080808, 0x1919082b08081919, - 0x1919082b08082b08, 0x1919082b08190819, 0x1919082b08191908, 0x1919082b082b0808, - 0x1919082b19080819, 0x1919082b19081908, 0x1919082b19190808, 0x1919082b192b2b19, - 0x1919082b2b080808, 0x1919190808080819, 0x1919190808081908, 0x191919080808192b, - 0x1919190808082b19, 0x1919190808190808, 0x191919080819082b, 0x1919190808191919, - 0x1919190808192b08, 0x19191908082b0819, 0x19191908082b1908, 0x1919190819080808, - 0x191919081908082b, 0x1919190819081919, 0x1919190819082b08, 0x1919190819190819, - 0x1919190819191908, 0x19191908192b0808, 0x191919082b080819, 0x191919082b081908, - 0x191919082b190808, 0x1919191908080808, 0x191919190808082b, 0x1919191908081919, - 0x1919191908082b08, 0x1919191908190819, 0x1919191908191908, 0x19191919082b0808, - 0x1919191919080819, 0x1919191919081908, 0x1919191919190808, 0x191919192b080808, - 0x1919192b08080819, 0x1919192b08081908, 0x1919192b08190808, 0x1919192b082b192b, - 0x1919192b19080808, 0x19192b0808080808, 0x19192b080808082b, 0x19192b0808081919, - 0x19192b0808082b08, 0x19192b0808190819, 0x19192b0808191908, 0x19192b08082b0808, - 0x19192b0819080819, 0x19192b0819081908, 0x19192b0819190808, 0x19192b0819192b2b, - 0x19192b082b080808, 0x19192b1908080819, 0x19192b1908081908, 0x19192b1908190808, - 0x19192b1919080808, 0x19192b2b08080808, 0x19192b2b08192b19, 0x19192b2b2b081919, - 0x19192b2b2b2b2b08, 0x192b080808080819, 0x192b080808081908, 0x192b08080808192b, - 0x192b080808190808, 0x192b08080819082b, 0x192b080808191919, 0x192b080808192b08, - 0x192b0808082b0819, 0x192b0808082b1908, 0x192b080819080808, 0x192b080819081919, - 0x192b080819082b08, 0x192b080819190819, 0x192b080819191908, 0x192b0808192b0808, - 0x192b08082b081908, 0x192b08082b190808, 0x192b081908080808, 0x192b08190808082b, - 0x192b081908081919, 0x192b081908082b08, 0x192b081908190819, 0x192b081908191908, - 0x192b0819082b0808, 0x192b081919080819, 0x192b081919081908, 0x192b081919190808, - 0x192b08192b080808, 0x192b08192b192b19, 0x192b082b08081908, 0x192b082b08190808, - 0x192b082b19080808, 0x192b082b1919192b, 0x192b082b2b2b0819, 0x192b190808080808, - 0x192b190808081919, 0x192b190808082b08, 0x192b190808190819, 0x192b190808191908, - 0x192b1908082b0808, 0x192b190819080819, 0x192b190819081908, 0x192b190819190808, - 0x192b19082b080808, 0x192b191908080819, 0x192b191908081908, 0x192b191908190808, - 0x192b191919080808, 0x192b191919082b2b, 0x192b1919192b2b08, 0x192b19192b19082b, - 0x192b192b08080808, 0x192b192b2b191908, 0x192b2b0808080819, 0x192b2b0808081908, - 0x192b2b0808190808, 0x192b2b08192b1919, 0x192b2b082b192b08, 0x192b2b1908080808, - 0x192b2b19082b2b2b, 0x192b2b2b1908082b, 0x192b2b2b2b2b0819, 0x2b08080808080808, - 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819, - 0x2b08080808191908, 0x2b08080808192b19, 0x2b080808082b0808, 0x2b080808082b1919, - 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808081919082b, - 0x2b08080819191919, 0x2b08080819192b08, 0x2b080808192b0819, 0x2b0808082b080808, - 0x2b0808082b081919, 0x2b0808082b190819, 0x2b0808082b191908, 0x2b08081908080819, - 0x2b08081908081908, 0x2b08081908082b19, 0x2b08081908190808, 0x2b0808190819082b, - 0x2b08081908191919, 0x2b08081908192b08, 0x2b080819082b0819, 0x2b080819082b1908, - 0x2b08081919080808, 0x2b0808191908082b, 0x2b08081919081919, 0x2b08081919082b08, - 0x2b08081919190819, 0x2b08081919191908, 0x2b0808192b080819, 0x2b0808192b081908, - 0x2b0808192b190808, 0x2b0808192b2b2b19, 0x2b08082b08080808, 0x2b08082b08081919, - 0x2b08082b08082b2b, 0x2b08082b08190819, 0x2b08082b08191908, 0x2b08082b19080819, - 0x2b08082b19081908, 0x2b08082b19190808, 0x2b08190808080819, 0x2b08190808081908, - 0x2b0819080808192b, 0x2b08190808082b19, 0x2b08190808190808, 0x2b0819080819082b, - 0x2b08190808191919, 0x2b08190808192b08, 0x2b081908082b0819, 0x2b08190819080808, - 0x2b0819081908082b, 0x2b08190819081919, 0x2b08190819082b08, 0x2b08190819190819, - 0x2b08190819191908, 0x2b081908192b0808, 0x2b0819082b080819, 0x2b0819082b081908, - 0x2b0819082b190808, 0x2b08191908080808, 0x2b0819190808082b, 0x2b08191908081919, - 0x2b08191908082b08, 0x2b08191908190819, 0x2b08191908191908, 0x2b081919082b0808, - 0x2b08191919080819, 0x2b08191919081908, 0x2b08191919190808, 0x2b0819192b080808, - 0x2b0819192b082b2b, 0x2b08192b08080819, 0x2b08192b08081908, 0x2b08192b08190808, - 0x2b08192b082b2b19, 0x2b08192b19080808, 0x2b082b0808080808, 0x2b082b0808081919, - 0x2b082b0808190819, 0x2b082b0808191908, 0x2b082b0819080819, 0x2b082b0819081908, - 0x2b082b0819190808, 0x2b082b082b2b082b, 0x2b082b1908080819, 0x2b082b1908081908, - 0x2b082b1919080808, 0x2b082b19192b1919, 0x2b082b2b082b082b, 0x2b082b2b19192b08, - 0x2b082b2b19192b2b, 0x2b082b2b2b08082b, 0x2b082b2b2b2b082b, 0x2b19080808080819, - 0x2b19080808081908, 0x2b19080808082b19, 0x2b19080808190808, 0x2b1908080819082b, - 0x2b19080808191919, 0x2b19080808192b08, 0x2b190808082b1908, 0x2b19080819080808, - 0x2b1908081908082b, 0x2b19080819081919, 0x2b19080819082b08, 0x2b19080819190819, - 0x2b19080819191908, 0x2b190808192b0808, 0x2b1908082b080819, 0x2b1908082b081908, - 0x2b1908082b190808, 0x2b19081908080808, 0x2b19081908081919, 0x2b19081908190819, - 0x2b19081908191908, 0x2b19081919080819, 0x2b19081919081908, 0x2b19081919190808, - 0x2b19081919192b2b, 0x2b19082b08080819, 0x2b19082b08081908, 0x2b19082b08190808, - 0x2b19082b19080808, 0x2b19082b2b2b192b, 0x2b19190808080808, 0x2b1919080808082b, - 0x2b19190808081919, 0x2b19190808082b08, 0x2b19190808190819, 0x2b19190808191908, - 0x2b191908082b0808, 0x2b19190819080819, 0x2b19190819081908, 0x2b19190819190808, - 0x2b1919082b080808, 0x2b1919082b19192b, 0x2b19191908080819, 0x2b19191908081908, - 0x2b19191908190808, 0x2b19191919080808, 0x2b1919192b192b08, 0x2b1919192b2b0819, - 0x2b19192b08080808, 0x2b19192b1908192b, 0x2b19192b192b1908, 0x2b192b0808080819, - 0x2b192b0808081908, 0x2b192b0808190808, 0x2b192b08082b192b, 0x2b192b0819080808, - 0x2b192b082b2b2b19, 0x2b192b1908080808, 0x2b192b1919082b19, 0x2b192b191919082b, - 0x2b192b2b2b190808, 0x2b2b080808080808, 0x2b2b080808081919, 0x2b2b080808082b2b, - 0x2b2b080808191908, 0x2b2b0808082b082b, 0x2b2b0808082b2b2b, 0x2b2b080819080819, - 0x2b2b080819081908, 0x2b2b080819190808, 0x2b2b08082b2b082b, 0x2b2b08082b2b2b2b, - 0x2b2b081919080808, 0x2b2b0819192b1919, 0x2b2b082b0808082b, 0x2b2b082b08082b2b, - 0x2b2b082b082b082b, 0x2b2b082b082b2b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b08082b, - 0x2b2b082b2b082b08, 0x2b2b082b2b082b2b, 0x2b2b082b2b2b2b08, 0x2b2b190808080819, - 0x2b2b190808081908, 0x2b2b190808190808, 0x2b2b190819080808, 0x2b2b19082b082b19, - 0x2b2b19082b2b1908, 0x2b2b191908080808, 0x2b2b191908192b19, 0x2b2b192b19190819, - 0x2b2b2b0808082b2b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b082b, 0x2b2b2b1919191908, - 0x2b2b2b192b08192b, 0x2b2b2b2b08082b08, 0x2b2b2b2b08082b2b, 0x2b2b2b2b082b0808, - 0x2b2b2b2b082b082b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b2b082b08, 0x2b2b2b2b2b2b2b2b, -}; - -static const __device__ uint32_t iq3xxs_grid[256] = { - 0x04040404, 0x04040414, 0x04040424, 0x04040c0c, 0x04040c1c, 0x04040c3e, 0x04041404, 0x04041414, - 0x04041c0c, 0x04042414, 0x04043e1c, 0x04043e2c, 0x040c040c, 0x040c041c, 0x040c0c04, 0x040c0c14, - 0x040c140c, 0x040c142c, 0x040c1c04, 0x040c1c14, 0x040c240c, 0x040c2c24, 0x040c3e04, 0x04140404, - 0x04140414, 0x04140424, 0x04140c0c, 0x04141404, 0x04141414, 0x04141c0c, 0x04141c1c, 0x04141c3e, - 0x04142c0c, 0x04142c3e, 0x04143e2c, 0x041c040c, 0x041c043e, 0x041c0c04, 0x041c0c14, 0x041c142c, - 0x041c3e04, 0x04240c1c, 0x04241c3e, 0x04242424, 0x04242c3e, 0x04243e1c, 0x04243e2c, 0x042c040c, - 0x042c043e, 0x042c1c14, 0x042c2c14, 0x04341c2c, 0x04343424, 0x043e0c04, 0x043e0c24, 0x043e0c34, - 0x043e241c, 0x043e340c, 0x0c04040c, 0x0c04041c, 0x0c040c04, 0x0c040c14, 0x0c04140c, 0x0c04141c, - 0x0c041c04, 0x0c041c14, 0x0c041c24, 0x0c04243e, 0x0c042c04, 0x0c0c0404, 0x0c0c0414, 0x0c0c0c0c, - 0x0c0c1404, 0x0c0c1414, 0x0c14040c, 0x0c14041c, 0x0c140c04, 0x0c140c14, 0x0c14140c, 0x0c141c04, - 0x0c143e14, 0x0c1c0404, 0x0c1c0414, 0x0c1c1404, 0x0c1c1c0c, 0x0c1c2434, 0x0c1c3434, 0x0c24040c, - 0x0c24042c, 0x0c242c04, 0x0c2c1404, 0x0c2c1424, 0x0c2c2434, 0x0c2c3e0c, 0x0c34042c, 0x0c3e1414, - 0x0c3e2404, 0x14040404, 0x14040414, 0x14040c0c, 0x14040c1c, 0x14041404, 0x14041414, 0x14041434, - 0x14041c0c, 0x14042414, 0x140c040c, 0x140c041c, 0x140c042c, 0x140c0c04, 0x140c0c14, 0x140c140c, - 0x140c1c04, 0x140c341c, 0x140c343e, 0x140c3e04, 0x14140404, 0x14140414, 0x14140c0c, 0x14140c3e, - 0x14141404, 0x14141414, 0x14141c3e, 0x14142404, 0x14142c2c, 0x141c040c, 0x141c0c04, 0x141c0c24, - 0x141c3e04, 0x141c3e24, 0x14241c2c, 0x14242c1c, 0x142c041c, 0x142c143e, 0x142c240c, 0x142c3e24, - 0x143e040c, 0x143e041c, 0x143e0c34, 0x143e242c, 0x1c04040c, 0x1c040c04, 0x1c040c14, 0x1c04140c, - 0x1c04141c, 0x1c042c04, 0x1c04342c, 0x1c043e14, 0x1c0c0404, 0x1c0c0414, 0x1c0c1404, 0x1c0c1c0c, - 0x1c0c2424, 0x1c0c2434, 0x1c14040c, 0x1c14041c, 0x1c140c04, 0x1c14142c, 0x1c142c14, 0x1c143e14, - 0x1c1c0c0c, 0x1c1c1c1c, 0x1c241c04, 0x1c24243e, 0x1c243e14, 0x1c2c0404, 0x1c2c0434, 0x1c2c1414, - 0x1c2c2c2c, 0x1c340c24, 0x1c341c34, 0x1c34341c, 0x1c3e1c1c, 0x1c3e3404, 0x24040424, 0x24040c3e, - 0x24041c2c, 0x24041c3e, 0x24042c1c, 0x24042c3e, 0x240c3e24, 0x24141404, 0x24141c3e, 0x24142404, - 0x24143404, 0x24143434, 0x241c043e, 0x241c242c, 0x24240424, 0x24242c0c, 0x24243424, 0x242c142c, - 0x242c241c, 0x242c3e04, 0x243e042c, 0x243e0c04, 0x243e0c14, 0x243e1c04, 0x2c040c14, 0x2c04240c, - 0x2c043e04, 0x2c0c0404, 0x2c0c0434, 0x2c0c1434, 0x2c0c2c2c, 0x2c140c24, 0x2c141c14, 0x2c143e14, - 0x2c1c0414, 0x2c1c2c1c, 0x2c240c04, 0x2c24141c, 0x2c24143e, 0x2c243e14, 0x2c2c0414, 0x2c2c1c0c, - 0x2c342c04, 0x2c3e1424, 0x2c3e2414, 0x34041424, 0x34042424, 0x34042434, 0x34043424, 0x340c140c, - 0x340c340c, 0x34140c3e, 0x34143424, 0x341c1c04, 0x341c1c34, 0x34242424, 0x342c042c, 0x342c2c14, - 0x34341c1c, 0x343e041c, 0x343e140c, 0x3e04041c, 0x3e04042c, 0x3e04043e, 0x3e040c04, 0x3e041c14, - 0x3e042c14, 0x3e0c1434, 0x3e0c2404, 0x3e140c14, 0x3e14242c, 0x3e142c14, 0x3e1c0404, 0x3e1c0c2c, - 0x3e1c1c1c, 0x3e1c3404, 0x3e24140c, 0x3e24240c, 0x3e2c0404, 0x3e2c0414, 0x3e2c1424, 0x3e341c04, -}; - -static const __device__ uint32_t iq3xs_grid[512] = { - 0x04040404, 0x0404040c, 0x04040414, 0x0404042c, 0x0404043e, 0x04040c04, 0x04040c0c, 0x04040c14, - 0x04040c24, 0x04040c34, 0x04041404, 0x0404140c, 0x0404142c, 0x04041c1c, 0x04042404, 0x04042414, - 0x0404242c, 0x0404243e, 0x04042c0c, 0x04042c1c, 0x04043404, 0x04043414, 0x04043e0c, 0x04043e24, - 0x04043e3e, 0x040c0404, 0x040c040c, 0x040c0414, 0x040c0424, 0x040c0c04, 0x040c0c0c, 0x040c0c2c, - 0x040c1404, 0x040c141c, 0x040c143e, 0x040c1c0c, 0x040c1c2c, 0x040c2424, 0x040c340c, 0x040c342c, - 0x040c3e14, 0x04140404, 0x0414040c, 0x0414042c, 0x0414043e, 0x04140c04, 0x04140c1c, 0x04140c34, - 0x0414140c, 0x0414142c, 0x04141c04, 0x04141c24, 0x04142414, 0x0414242c, 0x0414243e, 0x04142c0c, - 0x04142c1c, 0x04143e04, 0x04143e1c, 0x041c041c, 0x041c0c0c, 0x041c0c2c, 0x041c1404, 0x041c1414, - 0x041c1c0c, 0x041c1c1c, 0x041c1c34, 0x041c2424, 0x041c2c04, 0x041c2c14, 0x041c343e, 0x041c3e0c, - 0x041c3e2c, 0x04240404, 0x04240c1c, 0x04240c3e, 0x0424140c, 0x04241424, 0x04241c14, 0x04242404, - 0x0424241c, 0x04242c0c, 0x04243e04, 0x042c0414, 0x042c0424, 0x042c1404, 0x042c1414, 0x042c1434, - 0x042c1c1c, 0x042c240c, 0x042c242c, 0x042c243e, 0x042c3434, 0x042c3e1c, 0x04340434, 0x04340c0c, - 0x04340c1c, 0x04341c0c, 0x04342c14, 0x04343e0c, 0x043e0404, 0x043e0414, 0x043e0424, 0x043e1404, - 0x043e1414, 0x043e1434, 0x043e1c1c, 0x043e2c04, 0x043e2c24, 0x0c040404, 0x0c04040c, 0x0c040414, - 0x0c040424, 0x0c040c04, 0x0c040c0c, 0x0c040c1c, 0x0c040c2c, 0x0c040c3e, 0x0c041404, 0x0c041414, - 0x0c041c0c, 0x0c041c24, 0x0c041c34, 0x0c042c24, 0x0c042c34, 0x0c04340c, 0x0c043e14, 0x0c0c0404, - 0x0c0c040c, 0x0c0c041c, 0x0c0c0434, 0x0c0c0c04, 0x0c0c0c24, 0x0c0c140c, 0x0c0c1c04, 0x0c0c1c1c, - 0x0c0c240c, 0x0c0c2c04, 0x0c0c2c14, 0x0c0c3e04, 0x0c0c3e34, 0x0c140404, 0x0c140c14, 0x0c140c2c, - 0x0c140c3e, 0x0c141404, 0x0c141424, 0x0c141c14, 0x0c142404, 0x0c14241c, 0x0c142c2c, 0x0c143404, - 0x0c143e14, 0x0c1c040c, 0x0c1c0424, 0x0c1c043e, 0x0c1c0c04, 0x0c1c0c1c, 0x0c1c140c, 0x0c1c143e, - 0x0c1c1c04, 0x0c1c1c24, 0x0c1c240c, 0x0c1c3414, 0x0c1c3e04, 0x0c24041c, 0x0c24042c, 0x0c240c14, - 0x0c240c24, 0x0c241c0c, 0x0c241c1c, 0x0c242414, 0x0c242434, 0x0c242c04, 0x0c242c24, 0x0c2c040c, - 0x0c2c0c04, 0x0c2c0c1c, 0x0c2c140c, 0x0c2c1c04, 0x0c2c1c14, 0x0c2c2c0c, 0x0c341404, 0x0c341424, - 0x0c34143e, 0x0c342424, 0x0c342434, 0x0c3e040c, 0x0c3e041c, 0x0c3e0c04, 0x0c3e0c14, 0x0c3e140c, - 0x0c3e1c2c, 0x0c3e240c, 0x0c3e3414, 0x0c3e3e04, 0x14040404, 0x1404040c, 0x1404041c, 0x1404042c, - 0x1404043e, 0x14040c04, 0x14040c14, 0x14040c24, 0x14040c34, 0x1404140c, 0x1404141c, 0x1404143e, - 0x14041c04, 0x14041c14, 0x1404240c, 0x1404241c, 0x1404242c, 0x14042c04, 0x14042c14, 0x1404343e, - 0x14043e04, 0x14043e1c, 0x14043e2c, 0x140c0404, 0x140c0414, 0x140c0c04, 0x140c0c1c, 0x140c0c3e, - 0x140c1414, 0x140c142c, 0x140c1c0c, 0x140c1c24, 0x140c2414, 0x140c2c0c, 0x1414040c, 0x14140424, - 0x1414043e, 0x1414140c, 0x1414141c, 0x14141c04, 0x14141c3e, 0x1414240c, 0x14142c1c, 0x14142c3e, - 0x14143e0c, 0x14143e24, 0x141c0404, 0x141c0414, 0x141c042c, 0x141c0c0c, 0x141c1414, 0x141c1424, - 0x141c1c0c, 0x141c1c1c, 0x141c2414, 0x141c2c04, 0x141c3434, 0x1424040c, 0x1424043e, 0x14241404, - 0x1424141c, 0x14241c14, 0x14241c2c, 0x1424240c, 0x14243e14, 0x14243e2c, 0x142c0424, 0x142c0c0c, - 0x142c1414, 0x142c1c3e, 0x142c2404, 0x142c2c1c, 0x142c3e04, 0x14340404, 0x14340414, 0x1434043e, - 0x1434140c, 0x14342c2c, 0x1434340c, 0x143e042c, 0x143e0c0c, 0x143e1434, 0x143e1c04, 0x143e241c, - 0x143e2c04, 0x1c040414, 0x1c040c0c, 0x1c040c1c, 0x1c040c2c, 0x1c040c3e, 0x1c041414, 0x1c041c0c, - 0x1c041c1c, 0x1c041c2c, 0x1c042414, 0x1c042424, 0x1c04243e, 0x1c042c0c, 0x1c04341c, 0x1c043e0c, - 0x1c0c040c, 0x1c0c041c, 0x1c0c042c, 0x1c0c0c24, 0x1c0c140c, 0x1c0c141c, 0x1c0c2404, 0x1c0c3404, - 0x1c0c3e14, 0x1c0c3e34, 0x1c140404, 0x1c140c14, 0x1c141404, 0x1c141c14, 0x1c141c24, 0x1c142c04, - 0x1c1c040c, 0x1c1c0c04, 0x1c1c0c24, 0x1c1c140c, 0x1c1c141c, 0x1c1c143e, 0x1c1c1c04, 0x1c1c240c, - 0x1c1c241c, 0x1c1c243e, 0x1c1c2c2c, 0x1c1c3e1c, 0x1c24041c, 0x1c240c0c, 0x1c240c34, 0x1c241414, - 0x1c241c0c, 0x1c242c14, 0x1c243404, 0x1c243424, 0x1c2c040c, 0x1c2c0c04, 0x1c2c0c14, 0x1c2c142c, - 0x1c2c1c14, 0x1c2c2424, 0x1c2c2c34, 0x1c2c3e1c, 0x1c340c34, 0x1c34240c, 0x1c3e040c, 0x1c3e041c, - 0x1c3e1404, 0x1c3e1414, 0x1c3e1c2c, 0x24040404, 0x24040424, 0x24040c14, 0x24041404, 0x24041424, - 0x2404143e, 0x24041c14, 0x2404240c, 0x24042c04, 0x24043e04, 0x240c0414, 0x240c043e, 0x240c0c0c, - 0x240c0c1c, 0x240c1414, 0x240c1c04, 0x240c1c2c, 0x240c241c, 0x240c2c0c, 0x240c2c2c, 0x2414040c, - 0x2414041c, 0x24140c04, 0x24140c2c, 0x2414140c, 0x24141c1c, 0x24142404, 0x24142c3e, 0x24143414, - 0x24143e04, 0x241c0424, 0x241c0c0c, 0x241c0c1c, 0x241c1404, 0x241c1414, 0x241c1c0c, 0x241c1c2c, - 0x24240404, 0x24240414, 0x24241424, 0x24241c3e, 0x24242404, 0x24243e0c, 0x242c042c, 0x242c043e, - 0x242c140c, 0x242c3414, 0x24340c1c, 0x24341c24, 0x24343404, 0x243e0c04, 0x243e0c2c, 0x243e1c04, - 0x243e241c, 0x243e2c0c, 0x2c040414, 0x2c040c04, 0x2c040c24, 0x2c041414, 0x2c042404, 0x2c042424, - 0x2c04243e, 0x2c042c14, 0x2c043434, 0x2c043e24, 0x2c0c040c, 0x2c0c041c, 0x2c0c042c, 0x2c0c0c14, - 0x2c0c140c, 0x2c0c1c14, 0x2c0c3e14, 0x2c140404, 0x2c140c0c, 0x2c14141c, 0x2c141c04, 0x2c141c34, - 0x2c142c1c, 0x2c1c0414, 0x2c1c043e, 0x2c1c0c04, 0x2c1c143e, 0x2c1c2424, 0x2c1c2c0c, 0x2c1c342c, - 0x2c1c3e1c, 0x2c24040c, 0x2c240424, 0x2c241404, 0x2c241c14, 0x2c242434, 0x2c2c0c14, 0x2c2c1434, - 0x2c2c2c0c, 0x2c2c2c1c, 0x2c342414, 0x2c3e0414, 0x2c3e0424, 0x2c3e1414, 0x34040c0c, 0x34040c1c, - 0x34040c2c, 0x34041c0c, 0x34041c1c, 0x34043404, 0x340c0404, 0x340c1404, 0x340c143e, 0x340c3424, - 0x34140c14, 0x34141c24, 0x34142414, 0x34142c2c, 0x34143414, 0x34143e04, 0x341c0404, 0x341c0c24, - 0x341c140c, 0x341c2404, 0x3424142c, 0x3424241c, 0x34243414, 0x342c0404, 0x342c041c, 0x342c1c24, - 0x342c3404, 0x3434042c, 0x34342404, 0x343e0c0c, 0x343e0c1c, 0x3e040404, 0x3e040424, 0x3e04043e, - 0x3e041404, 0x3e041414, 0x3e041c34, 0x3e042404, 0x3e042c24, 0x3e043414, 0x3e0c0414, 0x3e0c0c0c, - 0x3e0c1424, 0x3e0c241c, 0x3e0c242c, 0x3e14040c, 0x3e140424, 0x3e140c04, 0x3e140c34, 0x3e14140c, - 0x3e141c04, 0x3e142c0c, 0x3e1c0414, 0x3e1c1c14, 0x3e1c1c2c, 0x3e1c2c1c, 0x3e24040c, 0x3e24042c, - 0x3e240c1c, 0x3e241404, 0x3e242c04, 0x3e2c1414, 0x3e2c2414, 0x3e340414, 0x3e341c0c, 0x3e3e0404, -}; - -#define IQ1S_DELTA 0.125f -#define IQ1M_DELTA 0.125f -static const __device__ uint64_t iq1s_grid_gpu[2048] = { - 0x00000000, 0x00000002, 0x00000101, 0x00000200, 0x00000202, 0x00010001, 0x00010101, 0x00020000, - 0x00020002, 0x00020200, 0x00020202, 0x01000101, 0x01010001, 0x01010100, 0x01010102, 0x01020101, - 0x02000000, 0x02000002, 0x02000200, 0x02000202, 0x02010101, 0x02020000, 0x02020002, 0x02020200, - 0x02020202, 0x00000110, 0x00000111, 0x00010011, 0x00010110, 0x00010112, 0x00010211, 0x00010212, - 0x00020111, 0x01000011, 0x01000112, 0x01000211, 0x01010012, 0x01010111, 0x01010212, 0x01020011, - 0x01020110, 0x01020112, 0x01020210, 0x02000111, 0x02010011, 0x02010110, 0x02010112, 0x02020111, - 0x00000020, 0x00000022, 0x00000220, 0x00000222, 0x00010121, 0x00020020, 0x00020022, 0x00020220, - 0x00020222, 0x01000121, 0x01010021, 0x01010221, 0x01020120, 0x01020221, 0x02000020, 0x02000022, - 0x02000220, 0x02000222, 0x02010021, 0x02010121, 0x02010221, 0x02020020, 0x02020022, 0x02020220, - 0x02020222, 0x00011001, 0x00011100, 0x00011102, 0x00021101, 0x01001001, 0x01001201, 0x01011101, - 0x01011202, 0x01021100, 0x01021101, 0x02011001, 0x02011201, 0x02021101, 0x00001011, 0x00001110, - 0x00001111, 0x00001112, 0x00011111, 0x00011210, 0x00011212, 0x00021211, 0x01001010, 0x01001111, - 0x01001212, 0x01011010, 0x01011011, 0x01011110, 0x01011111, 0x01011112, 0x01011211, 0x01021010, - 0x01021012, 0x01021111, 0x01021210, 0x01021212, 0x02001011, 0x02011011, 0x02011111, 0x02011210, - 0x02011212, 0x02021011, 0x02021110, 0x02021111, 0x02021112, 0x02021211, 0x00011120, 0x00011221, - 0x01001021, 0x01001120, 0x01011020, 0x01011022, 0x01011121, 0x01011220, 0x01021020, 0x01021021, - 0x01021122, 0x01021221, 0x02001121, 0x02011021, 0x02011120, 0x02011221, 0x00002000, 0x00002002, - 0x00002200, 0x00002202, 0x00012101, 0x00022000, 0x00022002, 0x00022200, 0x00022202, 0x01002101, - 0x01012001, 0x01012102, 0x01022101, 0x02002000, 0x02002002, 0x02002200, 0x02002202, 0x02012101, - 0x02022000, 0x02022002, 0x02022200, 0x02022202, 0x00002111, 0x00012011, 0x00012110, 0x00012211, - 0x00022110, 0x00022111, 0x01002011, 0x01012010, 0x01012011, 0x01012111, 0x01022011, 0x01022110, - 0x01022211, 0x02012011, 0x02012110, 0x02012112, 0x02012211, 0x02022111, 0x00002020, 0x00002022, - 0x00002220, 0x00002222, 0x00012121, 0x00022020, 0x00022022, 0x00022220, 0x00022222, 0x01002121, - 0x01012021, 0x01012221, 0x01022021, 0x01022121, 0x02002020, 0x02002022, 0x02002121, 0x02002220, - 0x02002222, 0x02012121, 0x02022020, 0x02022022, 0x02022220, 0x02022222, 0x00110000, 0x00110001, - 0x00110100, 0x00110201, 0x00120100, 0x00120101, 0x01100001, 0x01100100, 0x01110000, 0x01110101, - 0x01110200, 0x01120001, 0x01120100, 0x01120101, 0x01120201, 0x02110001, 0x02110100, 0x02110102, - 0x02120001, 0x02120101, 0x00100011, 0x00100110, 0x00100112, 0x00100211, 0x00110010, 0x00110012, - 0x00110111, 0x00110210, 0x00120011, 0x00120110, 0x00120211, 0x01100111, 0x01100212, 0x01110010, - 0x01110011, 0x01110012, 0x01110110, 0x01110111, 0x01110112, 0x01110211, 0x01120010, 0x01120111, - 0x02100110, 0x02110012, 0x02110111, 0x02120011, 0x02120110, 0x00110021, 0x00110120, 0x00110122, - 0x00120121, 0x01100020, 0x01100122, 0x01100221, 0x01110022, 0x01110121, 0x01110220, 0x01110222, - 0x01120120, 0x01120122, 0x02100121, 0x02110021, 0x02110120, 0x02110122, 0x02120121, 0x00101001, - 0x00101102, 0x00101201, 0x00111100, 0x00111101, 0x00111200, 0x00111201, 0x00121001, 0x00121102, - 0x01101001, 0x01101101, 0x01101102, 0x01101200, 0x01101202, 0x01111001, 0x01111100, 0x01111101, - 0x01111102, 0x01111201, 0x01121002, 0x01121101, 0x01121200, 0x02101100, 0x02101201, 0x02111000, - 0x02111100, 0x02111101, 0x02111200, 0x02111201, 0x02111202, 0x02121001, 0x02121100, 0x02121101, - 0x02121201, 0x00101012, 0x00101111, 0x00101212, 0x00111011, 0x00111110, 0x00111111, 0x00111112, - 0x00111211, 0x00121010, 0x00121012, 0x00121111, 0x00121210, 0x00121212, 0x01101011, 0x01101110, - 0x01101111, 0x01101112, 0x01111011, 0x01111012, 0x01111110, 0x01111111, 0x01111112, 0x01111211, - 0x01111212, 0x01121011, 0x01121110, 0x01121111, 0x01121112, 0x01121211, 0x02101010, 0x02101012, - 0x02101110, 0x02101111, 0x02101210, 0x02101212, 0x02111010, 0x02111011, 0x02111110, 0x02111111, - 0x02111112, 0x02111211, 0x02111212, 0x02121010, 0x02121012, 0x02121111, 0x00101021, 0x00101120, - 0x00101121, 0x00101122, 0x00111121, 0x00111122, 0x00111220, 0x00111222, 0x00121021, 0x00121122, - 0x01101020, 0x01101022, 0x01101120, 0x01101121, 0x01101220, 0x01101222, 0x01111021, 0x01111121, - 0x01111122, 0x01111220, 0x01111221, 0x01121021, 0x01121120, 0x01121121, 0x01121220, 0x01121221, - 0x01121222, 0x02101122, 0x02101222, 0x02111022, 0x02111121, 0x02121120, 0x02121221, 0x00112001, - 0x00112102, 0x00122101, 0x01102001, 0x01102100, 0x01102102, 0x01102201, 0x01112000, 0x01112101, - 0x01112200, 0x01112202, 0x01122000, 0x01122001, 0x01122100, 0x01122102, 0x01122201, 0x02102101, - 0x02112001, 0x02112100, 0x02122101, 0x00112010, 0x00112012, 0x00112111, 0x00112212, 0x00122011, - 0x00122111, 0x01102012, 0x01102110, 0x01102111, 0x01102210, 0x01112011, 0x01112110, 0x01112111, - 0x01112112, 0x01112211, 0x01112212, 0x01122010, 0x01122111, 0x01122212, 0x02102211, 0x02112011, - 0x02112012, 0x02112111, 0x02112210, 0x02122011, 0x02122112, 0x02122211, 0x00102221, 0x00112122, - 0x00122120, 0x00122122, 0x01102120, 0x01102122, 0x01102221, 0x01112020, 0x01112022, 0x01112121, - 0x01112220, 0x01122021, 0x01122122, 0x01122221, 0x02102121, 0x02112021, 0x02112122, 0x02112222, - 0x00200000, 0x00200002, 0x00200200, 0x00200202, 0x00210101, 0x00220000, 0x00220002, 0x00220101, - 0x00220200, 0x00220202, 0x01200101, 0x01210001, 0x01210201, 0x01220001, 0x01220101, 0x02200000, - 0x02200002, 0x02200200, 0x02200202, 0x02210101, 0x02220000, 0x02220002, 0x02220101, 0x02220200, - 0x02220202, 0x00200111, 0x00210011, 0x00210110, 0x00210211, 0x00220111, 0x01200012, 0x01200110, - 0x01200211, 0x01210111, 0x01210210, 0x01210212, 0x01220011, 0x01220110, 0x01220111, 0x01220112, - 0x02200111, 0x02210010, 0x02210112, 0x02210211, 0x02220111, 0x00200021, 0x00200220, 0x00200222, - 0x00210021, 0x00210121, 0x00220020, 0x00220022, 0x00220220, 0x00220222, 0x01200121, 0x01210021, - 0x01210122, 0x01210221, 0x01220121, 0x02200021, 0x02200220, 0x02200222, 0x02210021, 0x02210121, - 0x02220020, 0x02220022, 0x02220220, 0x02220222, 0x00201101, 0x00211100, 0x00211102, 0x00211201, - 0x00221101, 0x01201100, 0x01201101, 0x01201102, 0x01201201, 0x01211002, 0x01211101, 0x01211200, - 0x01211202, 0x01221102, 0x02201101, 0x02211001, 0x02211100, 0x02211201, 0x02221001, 0x02221101, - 0x00201211, 0x00211111, 0x00221011, 0x00221211, 0x01201010, 0x01201111, 0x01201210, 0x01211011, - 0x01211110, 0x01211111, 0x01211211, 0x01221012, 0x01221111, 0x01221210, 0x02201211, 0x02211010, - 0x02211110, 0x02211111, 0x02211210, 0x02211212, 0x02221011, 0x02221110, 0x02221112, 0x02221211, - 0x00201121, 0x00211020, 0x00211022, 0x00211221, 0x00221121, 0x01201021, 0x01201221, 0x01211121, - 0x01221020, 0x01221021, 0x01221221, 0x02201120, 0x02201122, 0x02211020, 0x02211222, 0x00202000, - 0x00202002, 0x00202200, 0x00202202, 0x00212101, 0x00222000, 0x00222002, 0x00222200, 0x00222202, - 0x01202101, 0x01212001, 0x01212100, 0x01222101, 0x02202000, 0x02202002, 0x02202200, 0x02202202, - 0x02222000, 0x02222002, 0x02222200, 0x02222202, 0x00202211, 0x00212011, 0x00212110, 0x00212211, - 0x00222111, 0x01202112, 0x01202211, 0x01212012, 0x01212111, 0x01222011, 0x01222110, 0x01222112, - 0x01222211, 0x02202111, 0x02212010, 0x02212112, 0x02212211, 0x02222110, 0x02222111, 0x00202020, - 0x00202022, 0x00202220, 0x00202222, 0x00222020, 0x00222022, 0x00222220, 0x00222222, 0x01202121, - 0x01212021, 0x01212122, 0x01212221, 0x01222121, 0x02202020, 0x02202022, 0x02202220, 0x02202222, - 0x02212121, 0x02222020, 0x02222022, 0x02222220, 0x02222222, 0x10000101, 0x10010001, 0x10010102, - 0x10020101, 0x11000201, 0x11010002, 0x11010101, 0x11010200, 0x11010202, 0x11020001, 0x11020100, - 0x11020102, 0x12010100, 0x12010201, 0x12020001, 0x12020102, 0x10000010, 0x10000011, 0x10000110, - 0x10000112, 0x10000211, 0x10010012, 0x10010111, 0x10010112, 0x10010210, 0x10010212, 0x10020011, - 0x10020112, 0x10020211, 0x11000111, 0x11000210, 0x11000212, 0x11010011, 0x11010110, 0x11010111, - 0x11010112, 0x11010211, 0x11010212, 0x11020111, 0x11020210, 0x11020212, 0x12000011, 0x12000110, - 0x12000112, 0x12010010, 0x12010012, 0x12010111, 0x12020010, 0x12020011, 0x12020012, 0x10000121, - 0x10010021, 0x10010120, 0x10010122, 0x10020121, 0x11000021, 0x11010022, 0x11010121, 0x11010222, - 0x11020120, 0x11020221, 0x12000221, 0x12010120, 0x12020121, 0x10001001, 0x10011101, 0x10011201, - 0x10021201, 0x11001101, 0x11001200, 0x11001202, 0x11011001, 0x11011100, 0x11011101, 0x11011102, - 0x11021001, 0x11021002, 0x11021101, 0x11021200, 0x11021202, 0x12001001, 0x12001102, 0x12001201, - 0x12011000, 0x12011002, 0x12011101, 0x12021000, 0x12021001, 0x12021201, 0x10001011, 0x10001012, - 0x10001111, 0x10001212, 0x10011011, 0x10011110, 0x10011111, 0x10011112, 0x10011211, 0x10021010, - 0x10021111, 0x10021212, 0x11001011, 0x11001110, 0x11001111, 0x11001112, 0x11001211, 0x11011010, - 0x11011011, 0x11011110, 0x11011111, 0x11011112, 0x11011210, 0x11011211, 0x11021011, 0x11021110, - 0x11021111, 0x11021112, 0x11021211, 0x12001012, 0x12001110, 0x12001111, 0x12001210, 0x12011011, - 0x12011110, 0x12011111, 0x12011112, 0x12011211, 0x12011212, 0x12021111, 0x12021210, 0x12021212, - 0x10001021, 0x10001121, 0x10001221, 0x10011120, 0x10011121, 0x10011220, 0x10011222, 0x10021021, - 0x10021120, 0x10021221, 0x11001020, 0x11001022, 0x11001121, 0x11001220, 0x11011020, 0x11011021, - 0x11011022, 0x11011121, 0x11011122, 0x11011221, 0x11021022, 0x11021121, 0x11021220, 0x12001021, - 0x12001121, 0x12001222, 0x12011120, 0x12011121, 0x12021021, 0x12021120, 0x12021122, 0x10002101, - 0x10012001, 0x10012101, 0x10012202, 0x10022101, 0x11002002, 0x11002201, 0x11012000, 0x11012101, - 0x11012200, 0x11022001, 0x11022100, 0x11022102, 0x11022201, 0x12002101, 0x12012001, 0x12012100, - 0x12012102, 0x12012201, 0x12022101, 0x10002011, 0x10002111, 0x10002112, 0x10002212, 0x10012010, - 0x10012110, 0x10012111, 0x10012210, 0x10022011, 0x10022110, 0x10022112, 0x11002010, 0x11002111, - 0x11002212, 0x11012011, 0x11012012, 0x11012110, 0x11012111, 0x11012112, 0x11012211, 0x11022010, - 0x11022012, 0x11022111, 0x11022112, 0x11022212, 0x12002112, 0x12002211, 0x12012012, 0x12012111, - 0x12012112, 0x12012210, 0x12022011, 0x12022110, 0x12022112, 0x12022211, 0x10012122, 0x11002120, - 0x11002122, 0x11002221, 0x11012121, 0x11012220, 0x11012222, 0x11022120, 0x11022221, 0x12012120, - 0x12022121, 0x10100001, 0x10100100, 0x10100101, 0x10100102, 0x10100201, 0x10110002, 0x10110101, - 0x10110202, 0x10120001, 0x10120100, 0x10120201, 0x11100000, 0x11100101, 0x11100200, 0x11110001, - 0x11110100, 0x11110101, 0x11110102, 0x11110201, 0x11120101, 0x11120200, 0x12100102, 0x12100201, - 0x12110101, 0x12110200, 0x12120000, 0x12120001, 0x12120102, 0x12120201, 0x10100111, 0x10100210, - 0x10100211, 0x10100212, 0x10110011, 0x10110110, 0x10110111, 0x10110112, 0x10110210, 0x10110211, - 0x10120010, 0x10120111, 0x10120112, 0x10120210, 0x10120212, 0x11100011, 0x11100110, 0x11100111, - 0x11100112, 0x11100211, 0x11110010, 0x11110011, 0x11110012, 0x11110110, 0x11110111, 0x11110112, - 0x11110210, 0x11110211, 0x11110212, 0x11120011, 0x11120110, 0x11120111, 0x11120112, 0x11120211, - 0x12100012, 0x12100111, 0x12110011, 0x12110110, 0x12110111, 0x12110112, 0x12110211, 0x12120010, - 0x12120111, 0x12120212, 0x10100021, 0x10100122, 0x10110022, 0x10110121, 0x10110222, 0x10120021, - 0x10120120, 0x11100022, 0x11100121, 0x11100222, 0x11110021, 0x11110120, 0x11110121, 0x11110122, - 0x11110221, 0x11120022, 0x11120121, 0x12100121, 0x12110020, 0x12110022, 0x12110121, 0x12110221, - 0x12110222, 0x12120120, 0x10101100, 0x10101101, 0x10111001, 0x10111100, 0x10111101, 0x10111102, - 0x10111200, 0x10111201, 0x10121001, 0x10121101, 0x10121200, 0x10121202, 0x11101001, 0x11101100, - 0x11101101, 0x11101102, 0x11101201, 0x11101202, 0x11111000, 0x11111001, 0x11111100, 0x11111101, - 0x11111102, 0x11111200, 0x11111201, 0x11111202, 0x11121001, 0x11121002, 0x11121100, 0x11121101, - 0x11121102, 0x11121201, 0x12101000, 0x12101200, 0x12101202, 0x12111001, 0x12111100, 0x12111101, - 0x12111102, 0x12111201, 0x12121001, 0x12121100, 0x12121101, 0x12121202, 0x10101011, 0x10101012, - 0x10101110, 0x10101111, 0x10101112, 0x10101211, 0x10111010, 0x10111011, 0x10111012, 0x10111110, - 0x10111111, 0x10111112, 0x10111211, 0x10111212, 0x10121011, 0x10121110, 0x10121111, 0x10121112, - 0x10121211, 0x11101010, 0x11101011, 0x11101012, 0x11101110, 0x11101111, 0x11101112, 0x11101210, - 0x11101211, 0x11111010, 0x11111011, 0x11111012, 0x11111110, 0x11111111, 0x11111112, 0x11111210, - 0x11111211, 0x11111212, 0x11121010, 0x11121011, 0x11121110, 0x11121111, 0x11121112, 0x11121210, - 0x11121211, 0x11121212, 0x12101011, 0x12101110, 0x12101111, 0x12101211, 0x12101212, 0x12111010, - 0x12111011, 0x12111110, 0x12111111, 0x12111112, 0x12111210, 0x12111211, 0x12121011, 0x12121110, - 0x12121111, 0x12121112, 0x12121211, 0x10101020, 0x10101021, 0x10101022, 0x10101120, 0x10101122, - 0x10101220, 0x10101221, 0x10111021, 0x10111120, 0x10111121, 0x10111220, 0x10111221, 0x10121020, - 0x10121021, 0x10121022, 0x10121120, 0x10121121, 0x10121122, 0x10121220, 0x10121221, 0x11101021, - 0x11101121, 0x11101122, 0x11101220, 0x11101221, 0x11101222, 0x11111020, 0x11111021, 0x11111022, - 0x11111120, 0x11111121, 0x11111122, 0x11111220, 0x11111221, 0x11111222, 0x11121021, 0x11121120, - 0x11121121, 0x11121221, 0x12101022, 0x12101121, 0x12101122, 0x12101220, 0x12101221, 0x12101222, - 0x12111021, 0x12111121, 0x12111222, 0x12121022, 0x12121121, 0x12121122, 0x12121220, 0x12121221, - 0x10102100, 0x10102101, 0x10102102, 0x10102201, 0x10112000, 0x10112101, 0x10112200, 0x10122001, - 0x10122202, 0x11102101, 0x11102200, 0x11102202, 0x11112001, 0x11112100, 0x11112101, 0x11112102, - 0x11112200, 0x11112201, 0x11122000, 0x11122002, 0x11122100, 0x11122101, 0x12102002, 0x12102201, - 0x12112000, 0x12112002, 0x12112101, 0x12112200, 0x12122001, 0x12122201, 0x10102011, 0x10102012, - 0x10102111, 0x10102212, 0x10112011, 0x10112110, 0x10112111, 0x10112112, 0x10112211, 0x10122111, - 0x11102011, 0x11102110, 0x11102111, 0x11102112, 0x11102211, 0x11112010, 0x11112011, 0x11112012, - 0x11112110, 0x11112111, 0x11112112, 0x11112210, 0x11112211, 0x11112212, 0x11122011, 0x11122110, - 0x11122111, 0x11122112, 0x11122211, 0x12102011, 0x12102111, 0x12102211, 0x12112011, 0x12112110, - 0x12112111, 0x12112112, 0x12112210, 0x12112211, 0x12122111, 0x10102120, 0x10102220, 0x10112121, - 0x10112222, 0x10122020, 0x10122121, 0x10122122, 0x10122221, 0x11102121, 0x11102220, 0x11102221, - 0x11112021, 0x11112121, 0x11112122, 0x11112220, 0x11112221, 0x11122022, 0x11122121, 0x11122220, - 0x11122222, 0x12102021, 0x12102222, 0x12112022, 0x12112121, 0x12112122, 0x12112220, 0x12112222, - 0x12122021, 0x10200101, 0x10210100, 0x10210102, 0x10210201, 0x10220101, 0x11200100, 0x11210000, - 0x11210101, 0x11210102, 0x11210200, 0x11210202, 0x11220001, 0x11220100, 0x11220102, 0x11220201, - 0x12200001, 0x12210102, 0x12220101, 0x10200011, 0x10200110, 0x10200112, 0x10200211, 0x10210012, - 0x10210111, 0x10220011, 0x10220012, 0x10220112, 0x10220211, 0x11200111, 0x11200211, 0x11210011, - 0x11210111, 0x11210112, 0x11210211, 0x11220111, 0x11220112, 0x11220212, 0x12200110, 0x12200212, - 0x12210012, 0x12210111, 0x12220011, 0x12220112, 0x12220211, 0x10210021, 0x10210122, 0x10210221, - 0x11200020, 0x11200021, 0x11200122, 0x11210121, 0x11210122, 0x11210220, 0x11220020, 0x12200121, - 0x12210021, 0x12210122, 0x12220121, 0x10211001, 0x10211002, 0x10211101, 0x10211102, 0x10211202, - 0x10221001, 0x10221102, 0x10221201, 0x11201000, 0x11201002, 0x11201101, 0x11201200, 0x11201202, - 0x11211001, 0x11211100, 0x11211101, 0x11211102, 0x11211201, 0x11211202, 0x11221000, 0x11221002, - 0x11221101, 0x12201100, 0x12201101, 0x12201201, 0x12211000, 0x12211002, 0x12211100, 0x12211101, - 0x12211102, 0x12211200, 0x12211202, 0x12221001, 0x12221100, 0x12221201, 0x10201111, 0x10201210, - 0x10201212, 0x10211011, 0x10211111, 0x10211112, 0x10211211, 0x11201110, 0x11201111, 0x11201112, - 0x11201211, 0x11211010, 0x11211011, 0x11211110, 0x11211111, 0x11211112, 0x11211211, 0x11221011, - 0x11221110, 0x11221111, 0x11221112, 0x11221211, 0x12201112, 0x12201211, 0x12201212, 0x12211011, - 0x12211111, 0x12211112, 0x12211211, 0x12211212, 0x12221012, 0x12221111, 0x12221112, 0x12221210, - 0x10201022, 0x10201221, 0x10211121, 0x10221020, 0x10221122, 0x10221220, 0x10221221, 0x11201020, - 0x11201121, 0x11201220, 0x11201222, 0x11211021, 0x11211120, 0x11211121, 0x11211122, 0x11211220, - 0x11211222, 0x11221020, 0x11221121, 0x11221220, 0x12201020, 0x12201022, 0x12201121, 0x12201222, - 0x12211120, 0x12211122, 0x12211220, 0x12211221, 0x12221020, 0x12221120, 0x12221122, 0x12221222, - 0x10212102, 0x10212201, 0x10222101, 0x11202001, 0x11212002, 0x11212101, 0x11212202, 0x11222001, - 0x11222201, 0x12202101, 0x12212001, 0x12212200, 0x12222102, 0x10202011, 0x10202110, 0x10212010, - 0x10212111, 0x10222011, 0x10222110, 0x10222112, 0x10222211, 0x11202010, 0x11202011, 0x11202111, - 0x11202112, 0x11202210, 0x11212011, 0x11212110, 0x11212111, 0x11212112, 0x11212211, 0x11222010, - 0x11222111, 0x11222212, 0x12202012, 0x12202110, 0x12202212, 0x12212111, 0x12222011, 0x12222110, - 0x12222111, 0x12222211, 0x10212021, 0x10212122, 0x10212220, 0x11202021, 0x11202120, 0x11202221, - 0x11212020, 0x11212121, 0x11212220, 0x11212222, 0x11222120, 0x11222121, 0x11222221, 0x12202122, - 0x12212120, 0x12212220, 0x12212222, 0x12222122, 0x20000000, 0x20000002, 0x20000200, 0x20000202, - 0x20020000, 0x20020002, 0x20020200, 0x20020202, 0x21000101, 0x21010000, 0x21010001, 0x21010100, - 0x21010102, 0x21010201, 0x21020101, 0x22000000, 0x22000002, 0x22000200, 0x22000202, 0x22010101, - 0x22020000, 0x22020002, 0x22020200, 0x22020202, 0x20000111, 0x20010011, 0x20010110, 0x20010112, - 0x20010211, 0x20020111, 0x21000011, 0x21000110, 0x21000211, 0x21010010, 0x21010012, 0x21010111, - 0x21010112, 0x21010210, 0x21010211, 0x21020110, 0x21020112, 0x21020211, 0x22000111, 0x22000211, - 0x22010110, 0x22010112, 0x22010211, 0x22020111, 0x20000020, 0x20000022, 0x20000220, 0x20000222, - 0x20010121, 0x20020020, 0x20020022, 0x20020220, 0x20020222, 0x21010021, 0x21010120, 0x21010221, - 0x21020121, 0x22000020, 0x22000022, 0x22000220, 0x22000222, 0x22010121, 0x22020020, 0x22020022, - 0x22020220, 0x22020222, 0x20011100, 0x20011201, 0x21001001, 0x21001100, 0x21011001, 0x21011101, - 0x21011202, 0x21021001, 0x21021100, 0x21021201, 0x22011100, 0x22011201, 0x20001011, 0x20001211, - 0x20011012, 0x20011111, 0x20011212, 0x20021112, 0x20021211, 0x21001010, 0x21001011, 0x21001111, - 0x21001210, 0x21011011, 0x21011110, 0x21011111, 0x21011112, 0x21011211, 0x21011212, 0x21021111, - 0x21021112, 0x21021210, 0x21021212, 0x22001011, 0x22001110, 0x22001112, 0x22001211, 0x22011010, - 0x22011012, 0x22011111, 0x22011210, 0x22021112, 0x20011021, 0x20011122, 0x20011221, 0x20021121, - 0x21001021, 0x21001120, 0x21001221, 0x21001222, 0x21011020, 0x21011121, 0x21011221, 0x21011222, - 0x21021021, 0x21021122, 0x21021222, 0x22001121, 0x22011021, 0x22011222, 0x22021120, 0x20002000, - 0x20002002, 0x20002200, 0x20002202, 0x20012101, 0x20022000, 0x20022002, 0x20022200, 0x20022202, - 0x21002001, 0x21002101, 0x21012001, 0x21012100, 0x21012201, 0x21022101, 0x21022201, 0x22002000, - 0x22002002, 0x22002200, 0x22002202, 0x22012101, 0x22022000, 0x22022002, 0x22022200, 0x22022202, - 0x20002111, 0x20002112, 0x20012011, 0x20012110, 0x20012112, 0x20022111, 0x21002011, 0x21002110, - 0x21002112, 0x21002211, 0x21012010, 0x21012012, 0x21012111, 0x21012212, 0x21022011, 0x21022110, - 0x22002111, 0x22012112, 0x22012211, 0x22022111, 0x20002020, 0x20002022, 0x20002220, 0x20002222, - 0x20012121, 0x20022020, 0x20022022, 0x20022220, 0x20022222, 0x21002121, 0x21012021, 0x21012120, - 0x21012122, 0x22002020, 0x22002022, 0x22002220, 0x22002222, 0x22012121, 0x22022020, 0x22022022, - 0x22022220, 0x22022222, 0x20100101, 0x20110001, 0x20110102, 0x20110200, 0x20110201, 0x20120101, - 0x21100001, 0x21100102, 0x21100201, 0x21110101, 0x21110200, 0x21110202, 0x21120201, 0x21120202, - 0x22100101, 0x22110001, 0x22110100, 0x22110102, 0x22110201, 0x22120101, 0x20100011, 0x20100110, - 0x20100112, 0x20100211, 0x20110010, 0x20110111, 0x20110210, 0x20110212, 0x20120011, 0x20120110, - 0x20120112, 0x20120211, 0x21100010, 0x21100111, 0x21110010, 0x21110011, 0x21110110, 0x21110111, - 0x21110112, 0x21110211, 0x21120012, 0x21120111, 0x22100110, 0x22100112, 0x22110012, 0x22110111, - 0x22110210, 0x22120011, 0x22120110, 0x22120112, 0x22120211, 0x20100121, 0x20110021, 0x20110120, - 0x20110221, 0x20120121, 0x21100120, 0x21100122, 0x21100221, 0x21110020, 0x21110022, 0x21110121, - 0x21110220, 0x21120122, 0x21120221, 0x22100121, 0x22110120, 0x22110122, 0x22120221, 0x20101001, - 0x20101100, 0x20101102, 0x20111000, 0x20111101, 0x20111200, 0x20121102, 0x21101000, 0x21101202, - 0x21111001, 0x21111100, 0x21111101, 0x21111102, 0x21111200, 0x21111201, 0x21121000, 0x21121001, - 0x21121002, 0x21121101, 0x22101100, 0x22101102, 0x22111002, 0x22111100, 0x22111101, 0x22111200, - 0x22121001, 0x22121201, 0x20101010, 0x20101111, 0x20101210, 0x20101212, 0x20111010, 0x20111011, - 0x20111110, 0x20111111, 0x20111112, 0x20111211, 0x20121011, 0x20121111, 0x20121211, 0x20121212, - 0x21101011, 0x21101110, 0x21101111, 0x21101112, 0x21101211, 0x21111010, 0x21111011, 0x21111012, - 0x21111110, 0x21111111, 0x21111112, 0x21111210, 0x21111211, 0x21111212, 0x21121011, 0x21121110, - 0x21121111, 0x21121112, 0x21121211, 0x22101011, 0x22101111, 0x22101210, 0x22111011, 0x22111012, - 0x22111110, 0x22111111, 0x22111112, 0x22111211, 0x22111212, 0x22121010, 0x22121012, 0x22121111, - 0x22121210, 0x22121212, 0x20101021, 0x20101120, 0x20111020, 0x20111121, 0x20111221, 0x20121020, - 0x20121122, 0x20121221, 0x21101121, 0x21101220, 0x21101221, 0x21111021, 0x21111022, 0x21111121, - 0x21111122, 0x21111221, 0x21121121, 0x21121220, 0x22101022, 0x22101120, 0x22101221, 0x22101222, - 0x22111022, 0x22111120, 0x22111121, 0x22121120, 0x22121122, 0x22121221, 0x20102101, 0x20112102, - 0x20112201, 0x20122101, 0x21102001, 0x21102102, 0x21112000, 0x21112002, 0x21112101, 0x21112102, - 0x21112202, 0x21122100, 0x21122101, 0x22102101, 0x22112001, 0x22112102, 0x22112201, 0x22122101, - 0x20102110, 0x20102112, 0x20102211, 0x20112010, 0x20112012, 0x20112111, 0x20112210, 0x20112212, - 0x20122010, 0x20122011, 0x20122110, 0x20122112, 0x21102010, 0x21102012, 0x21102111, 0x21102210, - 0x21102212, 0x21112011, 0x21112110, 0x21112111, 0x21112112, 0x21112211, 0x21122012, 0x21122111, - 0x21122112, 0x21122212, 0x22102011, 0x22102110, 0x22112010, 0x22112012, 0x22112111, 0x22112212, - 0x22122011, 0x22122112, 0x20102121, 0x20112121, 0x20122121, 0x21102120, 0x21102122, 0x21102221, - 0x21112020, 0x21112121, 0x21112220, 0x21122021, 0x22102121, 0x22112021, 0x22112120, 0x22112121, - 0x22112122, 0x20200000, 0x20200002, 0x20200200, 0x20200202, 0x20210101, 0x20220000, 0x20220002, - 0x20220200, 0x20220202, 0x21200101, 0x21210001, 0x21210100, 0x21210102, 0x21210201, 0x22200000, - 0x22200002, 0x22200200, 0x22200202, 0x22210101, 0x22220000, 0x22220002, 0x22220200, 0x22220202, - 0x20200111, 0x20200211, 0x20210011, 0x20210110, 0x20210112, 0x20210211, 0x20210212, 0x21200112, - 0x21200211, 0x21210011, 0x21210111, 0x21210210, 0x21210212, 0x21220011, 0x21220110, 0x22200111, - 0x22210010, 0x22210012, 0x22210112, 0x22210211, 0x20200022, 0x20200220, 0x20200222, 0x20210020, - 0x20210221, 0x20220022, 0x20220220, 0x20220222, 0x21200121, 0x21210021, 0x21210122, 0x21210221, - 0x21220121, 0x22200020, 0x22200022, 0x22200220, 0x22200222, 0x22210121, 0x22220020, 0x22220022, - 0x22220220, 0x22220222, 0x20211201, 0x20221101, 0x21201001, 0x21201100, 0x21211000, 0x21211100, - 0x21211101, 0x21211200, 0x21211202, 0x21221001, 0x21221101, 0x21221102, 0x21221200, 0x21221201, - 0x22201101, 0x20201112, 0x20201211, 0x20211010, 0x20211012, 0x20211111, 0x20211210, 0x20221112, - 0x20221211, 0x21201012, 0x21201111, 0x21211011, 0x21211110, 0x21211111, 0x21211112, 0x21211211, - 0x21221111, 0x21221212, 0x22201011, 0x22201110, 0x22201111, 0x22201112, 0x22201211, 0x22211012, - 0x22211111, 0x22211210, 0x20201121, 0x20211021, 0x20211122, 0x20211222, 0x20221021, 0x20221121, - 0x21201120, 0x21201122, 0x21201222, 0x21211022, 0x21211121, 0x21211122, 0x21211220, 0x21221020, - 0x21221022, 0x22201122, 0x22211020, 0x22211121, 0x22211122, 0x22211221, 0x22221021, 0x22221120, - 0x22221122, 0x20202000, 0x20202002, 0x20202200, 0x20202202, 0x20222000, 0x20222002, 0x20222200, - 0x20222202, 0x21212001, 0x21212100, 0x21212102, 0x21212201, 0x22202000, 0x22202002, 0x22202200, - 0x22202202, 0x22212101, 0x22222000, 0x22222002, 0x22222200, 0x22222202, 0x20202111, 0x20212110, - 0x20212211, 0x20222011, 0x20222111, 0x21202011, 0x21212010, 0x21212111, 0x21212212, 0x21222011, - 0x21222112, 0x21222211, 0x22212010, 0x22212112, 0x20202020, 0x20202022, 0x20202220, 0x20202222, - 0x20222020, 0x20222022, 0x20222220, 0x20222222, 0x21212021, 0x21212120, 0x21212122, 0x22202020, - 0x22202022, 0x22202220, 0x22202222, 0x22212121, 0x22222020, 0x22222022, 0x22222220, 0x22222222, -}; - -static const __device__ uint8_t ksigns_iq2xs[128] = { - 0, 129, 130, 3, 132, 5, 6, 135, 136, 9, 10, 139, 12, 141, 142, 15, - 144, 17, 18, 147, 20, 149, 150, 23, 24, 153, 154, 27, 156, 29, 30, 159, - 160, 33, 34, 163, 36, 165, 166, 39, 40, 169, 170, 43, 172, 45, 46, 175, - 48, 177, 178, 51, 180, 53, 54, 183, 184, 57, 58, 187, 60, 189, 190, 63, - 192, 65, 66, 195, 68, 197, 198, 71, 72, 201, 202, 75, 204, 77, 78, 207, - 80, 209, 210, 83, 212, 85, 86, 215, 216, 89, 90, 219, 92, 221, 222, 95, - 96, 225, 226, 99, 228, 101, 102, 231, 232, 105, 106, 235, 108, 237, 238, 111, - 240, 113, 114, 243, 116, 245, 246, 119, 120, 249, 250, 123, 252, 125, 126, 255, -}; - -static const __device__ uint64_t ksigns64[128] = { - 0x0000000000000000, 0xff000000000000ff, 0xff0000000000ff00, 0x000000000000ffff, - 0xff00000000ff0000, 0x0000000000ff00ff, 0x0000000000ffff00, 0xff00000000ffffff, - 0xff000000ff000000, 0x00000000ff0000ff, 0x00000000ff00ff00, 0xff000000ff00ffff, - 0x00000000ffff0000, 0xff000000ffff00ff, 0xff000000ffffff00, 0x00000000ffffffff, - 0xff0000ff00000000, 0x000000ff000000ff, 0x000000ff0000ff00, 0xff0000ff0000ffff, - 0x000000ff00ff0000, 0xff0000ff00ff00ff, 0xff0000ff00ffff00, 0x000000ff00ffffff, - 0x000000ffff000000, 0xff0000ffff0000ff, 0xff0000ffff00ff00, 0x000000ffff00ffff, - 0xff0000ffffff0000, 0x000000ffffff00ff, 0x000000ffffffff00, 0xff0000ffffffffff, - 0xff00ff0000000000, 0x0000ff00000000ff, 0x0000ff000000ff00, 0xff00ff000000ffff, - 0x0000ff0000ff0000, 0xff00ff0000ff00ff, 0xff00ff0000ffff00, 0x0000ff0000ffffff, - 0x0000ff00ff000000, 0xff00ff00ff0000ff, 0xff00ff00ff00ff00, 0x0000ff00ff00ffff, - 0xff00ff00ffff0000, 0x0000ff00ffff00ff, 0x0000ff00ffffff00, 0xff00ff00ffffffff, - 0x0000ffff00000000, 0xff00ffff000000ff, 0xff00ffff0000ff00, 0x0000ffff0000ffff, - 0xff00ffff00ff0000, 0x0000ffff00ff00ff, 0x0000ffff00ffff00, 0xff00ffff00ffffff, - 0xff00ffffff000000, 0x0000ffffff0000ff, 0x0000ffffff00ff00, 0xff00ffffff00ffff, - 0x0000ffffffff0000, 0xff00ffffffff00ff, 0xff00ffffffffff00, 0x0000ffffffffffff, - 0xffff000000000000, 0x00ff0000000000ff, 0x00ff00000000ff00, 0xffff00000000ffff, - 0x00ff000000ff0000, 0xffff000000ff00ff, 0xffff000000ffff00, 0x00ff000000ffffff, - 0x00ff0000ff000000, 0xffff0000ff0000ff, 0xffff0000ff00ff00, 0x00ff0000ff00ffff, - 0xffff0000ffff0000, 0x00ff0000ffff00ff, 0x00ff0000ffffff00, 0xffff0000ffffffff, - 0x00ff00ff00000000, 0xffff00ff000000ff, 0xffff00ff0000ff00, 0x00ff00ff0000ffff, - 0xffff00ff00ff0000, 0x00ff00ff00ff00ff, 0x00ff00ff00ffff00, 0xffff00ff00ffffff, - 0xffff00ffff000000, 0x00ff00ffff0000ff, 0x00ff00ffff00ff00, 0xffff00ffff00ffff, - 0x00ff00ffffff0000, 0xffff00ffffff00ff, 0xffff00ffffffff00, 0x00ff00ffffffffff, - 0x00ffff0000000000, 0xffffff00000000ff, 0xffffff000000ff00, 0x00ffff000000ffff, - 0xffffff0000ff0000, 0x00ffff0000ff00ff, 0x00ffff0000ffff00, 0xffffff0000ffffff, - 0xffffff00ff000000, 0x00ffff00ff0000ff, 0x00ffff00ff00ff00, 0xffffff00ff00ffff, - 0x00ffff00ffff0000, 0xffffff00ffff00ff, 0xffffff00ffffff00, 0x00ffff00ffffffff, - 0xffffffff00000000, 0x00ffffff000000ff, 0x00ffffff0000ff00, 0xffffffff0000ffff, - 0x00ffffff00ff0000, 0xffffffff00ff00ff, 0xffffffff00ffff00, 0x00ffffff00ffffff, - 0x00ffffffff000000, 0xffffffffff0000ff, 0xffffffffff00ff00, 0x00ffffffff00ffff, - 0xffffffffffff0000, 0x00ffffffffff00ff, 0x00ffffffffffff00, 0xffffffffffffffff, -}; - -static const __device__ uint8_t kmask_iq2xs[8] = {1, 2, 4, 8, 16, 32, 64, 128}; -static const __device__ int8_t kvalues_iq4nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113}; - - -typedef half dfloat; // dequantize float -typedef half2 dfloat2; -typedef void (*dequantize_kernel_t)(const void * vx, const int ib, const int iqs, dfloat2 & v); -template -using to_cuda_ggml_t = void (*)(const void * __restrict__ x, dst_t * __restrict__ y, int64_t k, cudaStream_t stream); -typedef float (*vec_dot_q_cuda_t)(const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs); -typedef void (*allocate_tiles_cuda_t)(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc); -typedef void (*load_tiles_cuda_t)( - const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, - int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row); -typedef float (*vec_dot_q_mul_mat_cuda_t)( - const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, - const int * __restrict__ y_qs, const half2 * __restrict__ y_ms, const int & i, const int & j, const int & k); - -// Utility function - -template -static __device__ __forceinline__ dst_t convert_from_half(half val) { - return val; -} - -template<> -__device__ __forceinline__ c10::BFloat16 convert_from_half(half val) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 - return __float2bfloat16(__half2float(val)); -#else - return __half2float(val); -#endif // defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 -} - -template<> -__device__ __forceinline__ float convert_from_half(half val) { - return __half2float(val); -} - -#if defined(USE_ROCM) - -#ifndef __has_builtin - #define __has_builtin(x) 0 -#endif - -typedef int8_t int8x4_t __attribute__((ext_vector_type(4))); -static __device__ __forceinline__ int __vsubss4(const int a, const int b) { - const int8x4_t va = reinterpret_cast(a); - const int8x4_t vb = reinterpret_cast(b); -#if __has_builtin(__builtin_elementwise_sub_sat) - const int8x4_t c = __builtin_elementwise_sub_sat(va, vb); - return reinterpret_cast(c); -#else - int8x4_t c; - int16_t tmp; -#pragma unroll - for (int i = 0; i < 4; i++) { - tmp = va[i] - vb[i]; - if(tmp > std::numeric_limits::max()) tmp = std::numeric_limits::max(); - if(tmp < std::numeric_limits::min()) tmp = std::numeric_limits::min(); - c[i] = tmp; - } - return reinterpret_cast(c); -#endif // __has_builtin(__builtin_elementwise_sub_sat) -} - -static __device__ __forceinline__ int __dp4a(const int a, const int b, int c) { -#if __has_builtin(__builtin_amdgcn_sdot4) - c = __builtin_amdgcn_sdot4(a, b, c, false); -#else - const int8x4_t va = reinterpret_cast(a); - const int8x4_t vb = reinterpret_cast(b); - c += va[0] * vb[0] + va[1] * vb[1] + va[2] * vb[2] + va[3] * vb[3]; -#endif - return c; -} - -static __device__ __forceinline__ uint32_t __vcmpeq4(const uint32_t a, const uint32_t b) { - uint32_t neq = a^b; - return !(neq & 0xff000000) * 0xff000000 | - !(neq & 0x00ff0000) * 0x00ff0000 | - !(neq & 0x0000ff00) * 0x0000ff00 | - !(neq & 0x000000ff) * 0x000000ff; -} - -static __device__ __forceinline__ uint32_t __vsub4(const uint32_t a, const uint32_t b) { - return (static_cast(((a & 0xff000000) >> 24) - ((b & 0xff000000) >> 24)) << 24) + - (static_cast(((a & 0x00ff0000) >> 16) - ((b & 0x00ff0000) >> 16)) << 16) + - (static_cast(((a & 0x0000ff00) >> 8) - ((b & 0x0000ff00) >> 8)) << 8) + - (static_cast(((a & 0x000000ff) >> 0) - ((b & 0x000000ff) >> 0)) << 0); -} -#endif // defined(USE_ROCM) diff --git a/csrc/libtorch_stable/quantization/gguf/gguf_kernel.cu b/csrc/libtorch_stable/quantization/gguf/gguf_kernel.cu deleted file mode 100644 index e90aa1565c52..000000000000 --- a/csrc/libtorch_stable/quantization/gguf/gguf_kernel.cu +++ /dev/null @@ -1,561 +0,0 @@ -#include -#include - -#include "../../../cuda_compat.h" -#include "../../dispatch_utils.h" -#include "../../torch_utils.h" - -#include - -#include "ggml-common.h" -#include "vecdotq.cuh" -#include "dequantize.cuh" -#include "mmvq.cuh" -#include "mmq.cuh" -#include "moe.cuh" -#include "moe_vec.cuh" - -// Q8 gemv -template -static __global__ void quantize_q8_1(const scalar_t* __restrict__ x, - void* __restrict__ vy, const int kx, - const int kx_padded) { - const auto ix = blockDim.x * blockIdx.x + threadIdx.x; - if (ix >= kx_padded) { - return; - } - const auto iy = blockDim.y * blockIdx.y + threadIdx.y; - const int i_padded = iy * kx_padded + ix; - - block_q8_1* y = (block_q8_1*)vy; - - const int ib = i_padded / QK8_1; // block index - const int iqs = i_padded % QK8_1; // quant index - - const float xi = ix < kx ? static_cast(x[iy * kx + ix]) : 0.0f; - float amax = fabsf(xi); - float sum = xi; - -#pragma unroll - for (int mask = 16; mask > 0; mask >>= 1) { - amax = fmaxf(amax, VLLM_SHFL_XOR_SYNC_WIDTH(amax, mask, 32)); - sum += VLLM_SHFL_XOR_SYNC_WIDTH(sum, mask, 32); - } - - const float d = amax / 127; - const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); - - y[ib].qs[iqs] = q; - - if (iqs > 0) { - return; - } - - y[ib].ds.x = __float2half(d); - y[ib].ds.y = __float2half(sum); -} - -template -static void quantize_row_q8_1_cuda(const scalar_t* x, void* vy, const int kx, - const int ky, cudaStream_t stream) { - const int64_t kx_padded = (kx + 512 - 1) / 512 * 512; - const int block_num_x = - (kx_padded + CUDA_QUANTIZE_BLOCK_SIZE - 1) / CUDA_QUANTIZE_BLOCK_SIZE; - constexpr int MAX_BLOCK_SIZE = 65535; - for (int off = 0; off < ky; off += MAX_BLOCK_SIZE) { - const int num_blocks_y = std::min(ky, off + MAX_BLOCK_SIZE) - off; - const dim3 num_blocks(block_num_x, num_blocks_y, 1); - const dim3 block_size(CUDA_DEQUANTIZE_BLOCK_SIZE, 1, 1); - quantize_q8_1<<>>( - &x[off * kx], (int32_t*)vy + off * (kx_padded / 32 * 9), kx, kx_padded); - } -} - -torch::stable::Tensor ggml_dequantize( - torch::stable::Tensor W, // quant weight - int64_t type, int64_t m, int64_t n, - std::optional const& dtype) { - const torch::stable::accelerator::DeviceGuard device_guard( - W.get_device_index()); - auto dtype_ = dtype.value_or(torch::headeronly::ScalarType::Half); - auto DW = torch::stable::empty({m, n}, dtype_, std::nullopt, W.device()); - torch::stable::fill_(DW, 0.0); - cudaStream_t stream = get_current_cuda_stream(); - - VLLM_STABLE_DISPATCH_FLOATING_TYPES(DW.scalar_type(), "ggml_dequantize", [&] { - auto to_cuda = ggml_get_to_cuda(type); - to_cuda((void*)W.data_ptr(), (scalar_t*)DW.data_ptr(), m * n, stream); - }); - - return DW; -} - -torch::stable::Tensor ggml_mul_mat_vec_a8( - torch::stable::Tensor W, // quant weight - torch::stable::Tensor X, // input - int64_t type, int64_t row) { - int64_t col = X.sizes()[1]; - int64_t vecs = X.sizes()[0]; - const int64_t padded = (col + 512 - 1) / 512 * 512; - const torch::stable::accelerator::DeviceGuard device_guard( - X.get_device_index()); - auto Y = torch::stable::empty({vecs, row}, X.scalar_type(), std::nullopt, - W.device()); - torch::stable::fill_(Y, 0.0); - cudaStream_t stream = get_current_cuda_stream(); - auto quant_X = torch::stable::empty({vecs, padded / 32 * 9}, - torch::headeronly::ScalarType::Int, - std::nullopt, W.device()); - VLLM_STABLE_DISPATCH_FLOATING_TYPES( - X.scalar_type(), "ggml_mul_mat_vec_a8", [&] { - quantize_row_q8_1_cuda((scalar_t*)X.data_ptr(), - (void*)quant_X.data_ptr(), col, vecs, - stream); - switch (type) { - case 2: - mul_mat_vec_q4_0_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 3: - mul_mat_vec_q4_1_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 6: - mul_mat_vec_q5_0_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 7: - mul_mat_vec_q5_1_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 8: - mul_mat_vec_q8_0_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 10: - mul_mat_vec_q2_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 11: - mul_mat_vec_q3_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 12: - mul_mat_vec_q4_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 13: - mul_mat_vec_q5_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 14: - mul_mat_vec_q6_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 16: - mul_mat_vec_iq2_xxs_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 17: - mul_mat_vec_iq2_xs_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 18: - mul_mat_vec_iq3_xxs_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 19: - mul_mat_vec_iq1_s_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 20: - mul_mat_vec_iq4_nl_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 21: - mul_mat_vec_iq3_s_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 22: - mul_mat_vec_iq2_s_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 23: - mul_mat_vec_iq4_xs_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - case 29: - mul_mat_vec_iq1_m_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, vecs, stream); - break; - } - }); - return Y; -} - -torch::stable::Tensor ggml_mul_mat_a8(torch::stable::Tensor W, // quant weight - torch::stable::Tensor X, // input - int64_t type, int64_t row) { - int64_t col = X.sizes()[1]; - int64_t padded = (col + 512 - 1) / 512 * 512; - int64_t batch = X.sizes()[0]; - const torch::stable::accelerator::DeviceGuard device_guard( - X.get_device_index()); - auto Y = torch::stable::empty({batch, row}, X.scalar_type(), std::nullopt, - W.device()); - torch::stable::fill_(Y, 0.0); - cudaStream_t stream = get_current_cuda_stream(); - auto quant_X = torch::stable::empty({batch, padded / 32 * 9}, - torch::headeronly::ScalarType::Int, - std::nullopt, W.device()); - VLLM_STABLE_DISPATCH_FLOATING_TYPES(X.scalar_type(), "ggml_mul_mat_a8", [&] { - quantize_row_q8_1_cuda((scalar_t*)X.data_ptr(), (void*)quant_X.data_ptr(), - col, batch, stream); - - switch (type) { - case 2: - ggml_mul_mat_q4_0_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, batch, padded, row, stream); - break; - case 3: - ggml_mul_mat_q4_1_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, batch, padded, row, stream); - break; - case 6: - ggml_mul_mat_q5_0_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, batch, padded, row, stream); - break; - case 7: - ggml_mul_mat_q5_1_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, batch, padded, row, stream); - break; - case 8: - ggml_mul_mat_q8_0_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, batch, padded, row, stream); - break; - case 10: - ggml_mul_mat_q2_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, batch, padded, row, stream); - break; - case 11: - ggml_mul_mat_q3_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, batch, padded, row, stream); - break; - case 12: - ggml_mul_mat_q4_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, batch, padded, row, stream); - break; - case 13: - ggml_mul_mat_q5_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, batch, padded, row, stream); - break; - case 14: - ggml_mul_mat_q6_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), col, row, batch, padded, row, stream); - break; - } - }); - return Y; -} - -torch::stable::Tensor ggml_moe_a8(torch::stable::Tensor X, // input - torch::stable::Tensor W, // expert weights - torch::stable::Tensor sorted_token_ids, - torch::stable::Tensor expert_ids, - torch::stable::Tensor num_tokens_post_padded, - int64_t type, int64_t row, int64_t top_k, - int64_t tokens) { - int64_t col = X.sizes()[1]; - int64_t padded = (col + 512 - 1) / 512 * 512; - const torch::stable::accelerator::DeviceGuard device_guard( - X.get_device_index()); - auto Y = torch::stable::empty({tokens * top_k, row}, X.scalar_type(), - std::nullopt, W.device()); - torch::stable::fill_(Y, 0.0); - cudaStream_t stream = get_current_cuda_stream(); - auto quant_X = torch::stable::empty({tokens, padded / 32 * 9}, - torch::headeronly::ScalarType::Int, - std::nullopt, W.device()); - VLLM_STABLE_DISPATCH_FLOATING_TYPES(X.scalar_type(), "ggml_moe_a8", [&] { - quantize_row_q8_1_cuda((scalar_t*)X.data_ptr(), (void*)quant_X.data_ptr(), - col, tokens, stream); - switch (type) { - case 2: - ggml_moe_q4_0_q8_1_cuda( - (void*)quant_X.data_ptr(), (void*)W.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)sorted_token_ids.data_ptr(), - (int*)expert_ids.data_ptr(), - (int*)num_tokens_post_padded.data_ptr(), W.stride(0), col, row, - tokens, padded, row, top_k, sorted_token_ids.sizes()[0], stream); - break; - case 3: - ggml_moe_q4_1_q8_1_cuda( - (void*)quant_X.data_ptr(), (void*)W.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)sorted_token_ids.data_ptr(), - (int*)expert_ids.data_ptr(), - (int*)num_tokens_post_padded.data_ptr(), W.stride(0), col, row, - tokens, padded, row, top_k, sorted_token_ids.sizes()[0], stream); - break; - case 6: - ggml_moe_q5_0_q8_1_cuda( - (void*)quant_X.data_ptr(), (void*)W.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)sorted_token_ids.data_ptr(), - (int*)expert_ids.data_ptr(), - (int*)num_tokens_post_padded.data_ptr(), W.stride(0), col, row, - tokens, padded, row, top_k, sorted_token_ids.sizes()[0], stream); - break; - case 7: - ggml_moe_q5_1_q8_1_cuda( - (void*)quant_X.data_ptr(), (void*)W.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)sorted_token_ids.data_ptr(), - (int*)expert_ids.data_ptr(), - (int*)num_tokens_post_padded.data_ptr(), W.stride(0), col, row, - tokens, padded, row, top_k, sorted_token_ids.sizes()[0], stream); - break; - case 8: - ggml_moe_q8_0_q8_1_cuda( - (void*)quant_X.data_ptr(), (void*)W.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)sorted_token_ids.data_ptr(), - (int*)expert_ids.data_ptr(), - (int*)num_tokens_post_padded.data_ptr(), W.stride(0), col, row, - tokens, padded, row, top_k, sorted_token_ids.sizes()[0], stream); - break; - case 10: - ggml_moe_q2_K_q8_1_cuda( - (void*)quant_X.data_ptr(), (void*)W.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)sorted_token_ids.data_ptr(), - (int*)expert_ids.data_ptr(), - (int*)num_tokens_post_padded.data_ptr(), W.stride(0), col, row, - tokens, padded, row, top_k, sorted_token_ids.sizes()[0], stream); - break; - case 11: - ggml_moe_q3_K_q8_1_cuda( - (void*)quant_X.data_ptr(), (void*)W.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)sorted_token_ids.data_ptr(), - (int*)expert_ids.data_ptr(), - (int*)num_tokens_post_padded.data_ptr(), W.stride(0), col, row, - tokens, padded, row, top_k, sorted_token_ids.sizes()[0], stream); - break; - case 12: - ggml_moe_q4_K_q8_1_cuda( - (void*)quant_X.data_ptr(), (void*)W.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)sorted_token_ids.data_ptr(), - (int*)expert_ids.data_ptr(), - (int*)num_tokens_post_padded.data_ptr(), W.stride(0), col, row, - tokens, padded, row, top_k, sorted_token_ids.sizes()[0], stream); - break; - case 13: - ggml_moe_q5_K_q8_1_cuda( - (void*)quant_X.data_ptr(), (void*)W.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)sorted_token_ids.data_ptr(), - (int*)expert_ids.data_ptr(), - (int*)num_tokens_post_padded.data_ptr(), W.stride(0), col, row, - tokens, padded, row, top_k, sorted_token_ids.sizes()[0], stream); - break; - case 14: - ggml_moe_q6_K_q8_1_cuda( - (void*)quant_X.data_ptr(), (void*)W.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)sorted_token_ids.data_ptr(), - (int*)expert_ids.data_ptr(), - (int*)num_tokens_post_padded.data_ptr(), W.stride(0), col, row, - tokens, padded, row, top_k, sorted_token_ids.sizes()[0], stream); - break; - } - }); - return Y; -} - -torch::stable::Tensor ggml_moe_a8_vec( - torch::stable::Tensor X, // input - torch::stable::Tensor W, // expert weights - torch::stable::Tensor topk_ids, int64_t top_k, int64_t type, int64_t row, - int64_t tokens) { - int64_t col = X.sizes()[1]; - const int64_t padded = (col + 512 - 1) / 512 * 512; - const torch::stable::accelerator::DeviceGuard device_guard( - X.get_device_index()); - auto Y = torch::stable::empty({tokens * top_k, row}, X.scalar_type(), - std::nullopt, W.device()); - torch::stable::fill_(Y, 0.0); - cudaStream_t stream = get_current_cuda_stream(); - auto quant_X = torch::stable::empty({tokens, padded / 32 * 9}, - torch::headeronly::ScalarType::Int, - std::nullopt, W.device()); - VLLM_STABLE_DISPATCH_FLOATING_TYPES(X.scalar_type(), "ggml_moe_vec_a8", [&] { - quantize_row_q8_1_cuda((scalar_t*)X.data_ptr(), - (void*)quant_X.data_ptr(), col, tokens, - stream); - switch (type) { - case 2: - moe_vec_q4_0_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 3: - moe_vec_q4_1_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 6: - moe_vec_q5_0_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 7: - moe_vec_q5_1_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 8: - moe_vec_q8_0_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 10: - moe_vec_q2_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 11: - moe_vec_q3_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 12: - moe_vec_q4_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 13: - moe_vec_q5_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 14: - moe_vec_q6_K_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 16: - moe_vec_iq2_xxs_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 17: - moe_vec_iq2_xs_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 18: - moe_vec_iq3_xxs_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 19: - moe_vec_iq1_s_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 20: - moe_vec_iq4_nl_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 21: - moe_vec_iq3_s_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 22: - moe_vec_iq2_s_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 23: - moe_vec_iq4_xs_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - case 29: - moe_vec_iq1_m_q8_1_cuda( - (void*)W.data_ptr(), (void*)quant_X.data_ptr(), - (scalar_t*)Y.data_ptr(), (int*)topk_ids.data_ptr(), top_k, tokens, - col, row, quant_X.stride(0), stream); - break; - } - }); - return Y; -} - -int64_t ggml_moe_get_block_size(int64_t type) { - switch (type) { - case 2: - return MOE_X_Q4_0; - case 3: - return MOE_X_Q4_1; - case 6: - return MOE_X_Q5_0; - case 7: - return MOE_X_Q5_1; - case 8: - return MOE_X_Q8_0; - case 10: - return MOE_X_Q2_K; - case 11: - return MOE_X_Q3_K; - case 12: - return MOE_X_Q4_K; - case 13: - return MOE_X_Q5_K; - case 14: - return MOE_X_Q6_K; - } - return 0; -} diff --git a/csrc/libtorch_stable/quantization/gguf/mmq.cuh b/csrc/libtorch_stable/quantization/gguf/mmq.cuh deleted file mode 100644 index 7c89918c23d8..000000000000 --- a/csrc/libtorch_stable/quantization/gguf/mmq.cuh +++ /dev/null @@ -1,610 +0,0 @@ -// copied from https://github.com/ggerganov/llama.cpp/blob/b2899/ggml-cuda/mmq.cu -template -static __device__ __forceinline__ void mul_mat_q( - const void * __restrict__ vx, const void * __restrict__ vy, scalar_t * __restrict__ dst, - const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { - - const block_q_t * x = (const block_q_t *) vx; - const block_q8_1 * y = (const block_q8_1 *) vy; - - const int blocks_per_row_x = ncols_x / qk; - const int blocks_per_col_y = nrows_y / QK8_1; - const int blocks_per_warp = WARP_SIZE_GGUF / qi; - - const int & ncols_dst = ncols_y; - - const auto row_dst_0 = blockIdx.x*mmq_y; - const int & row_x_0 = row_dst_0; - - const auto col_dst_0 = blockIdx.y*mmq_x; - const int & col_y_0 = col_dst_0; - - int * tile_x_ql = nullptr; - half2 * tile_x_dm = nullptr; - int * tile_x_qh = nullptr; - int * tile_x_sc = nullptr; - - allocate_tiles(&tile_x_ql, &tile_x_dm, &tile_x_qh, &tile_x_sc); - - __shared__ int tile_y_qs[mmq_x * WARP_SIZE_GGUF]; - __shared__ half2 tile_y_ds[mmq_x * WARP_SIZE_GGUF/QI8_1]; - - float sum[mmq_y/WARP_SIZE_GGUF][mmq_x/nwarps] = {{0.0f}}; - - for (int ib0 = 0; ib0 < blocks_per_row_x; ib0 += blocks_per_warp) { - - load_tiles(x + row_x_0*blocks_per_row_x + ib0, tile_x_ql, tile_x_dm, tile_x_qh, tile_x_sc, - threadIdx.y, nrows_x-row_x_0-1, threadIdx.x, blocks_per_row_x); - -#pragma unroll - for (int ir = 0; ir < qr && ib0 + ir * blocks_per_warp/qr < blocks_per_row_x; ++ir) { - const auto kqs = ir*WARP_SIZE_GGUF + threadIdx.x; - const int kbxd = kqs / QI8_1; - -#pragma unroll - for (int i = 0; i < mmq_x; i += nwarps) { - const int col_y_eff = min(col_y_0 + threadIdx.y + i, ncols_y-1); // to prevent out-of-bounds memory accesses - const block_q8_1 * by0 = &y[col_y_eff*blocks_per_col_y + ib0 * (qk/QK8_1) + kbxd]; - const int index_y = (threadIdx.y + i) * WARP_SIZE_GGUF + kqs % WARP_SIZE_GGUF; - tile_y_qs[index_y] = get_int_from_int8_aligned(by0->qs, threadIdx.x % QI8_1); - } - -#pragma unroll - for (int ids0 = 0; ids0 < mmq_x; ids0 += nwarps * QI8_1) { - const int ids = (ids0 + threadIdx.y * QI8_1 + threadIdx.x / (WARP_SIZE_GGUF/QI8_1)) % mmq_x; - const auto kby = threadIdx.x % (WARP_SIZE_GGUF/QI8_1); - const int col_y_eff = min(col_y_0 + ids, ncols_y-1); - - // if the sum is not needed it's faster to transform the scale to f32 ahead of time - const half2 * dsi_src = &y[col_y_eff*blocks_per_col_y + ib0 * (qk/QK8_1) + ir*(WARP_SIZE_GGUF/QI8_1) + kby].ds; - half2 * dsi_dst = &tile_y_ds[ids * (WARP_SIZE_GGUF/QI8_1) + kby]; - if (need_sum) { - *dsi_dst = *dsi_src; - } else { - float * dfi_dst = (float *) dsi_dst; - *dfi_dst = __low2float(*dsi_src); - } - } - - __syncthreads(); - -// #pragma unroll // unrolling this loop causes too much register pressure - for (int k = ir*WARP_SIZE_GGUF/qr; k < (ir+1)*WARP_SIZE_GGUF/qr; k += vdr) { -#pragma unroll - for (int j = 0; j < mmq_x; j += nwarps) { -#pragma unroll - for (int i = 0; i < mmq_y; i += WARP_SIZE_GGUF) { - sum[i/WARP_SIZE_GGUF][j/nwarps] += vec_dot( - tile_x_ql, tile_x_dm, tile_x_qh, tile_x_sc, tile_y_qs, tile_y_ds, - threadIdx.x + i, threadIdx.y + j, k); - } - } - } - __syncthreads(); - } - } - -#pragma unroll - for (int j = 0; j < mmq_x; j += nwarps) { - const auto col_dst = col_dst_0 + j + threadIdx.y; - if (col_dst >= ncols_dst) { - return; - } - -#pragma unroll - for (int i = 0; i < mmq_y; i += WARP_SIZE_GGUF) { - const auto row_dst = row_dst_0 + threadIdx.x + i; - if (row_dst >= nrows_dst) { - continue; - } - dst[col_dst*nrows_dst + row_dst] = sum[i/WARP_SIZE_GGUF][j/nwarps]; - } - } -} - -#if defined(USE_ROCM) -#define MMQ_X_Q4_0 64 -#define MMQ_Y_Q4_0 128 -#define NWARPS_Q4_0 8 -#else -#define MMQ_X_Q4_0 4 -#define MMQ_Y_Q4_0 32 -#define NWARPS_Q4_0 4 -#endif - -template static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF*NWARPS_Q4_0, 2) -#endif -mul_mat_q4_0( - const void * __restrict__ vx, const void * __restrict__ vy, scalar_t * __restrict__ dst, - const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { - const int mmq_x = MMQ_X_Q4_0; - const int mmq_y = MMQ_Y_Q4_0; - const int nwarps = NWARPS_Q4_0; - - mul_mat_q, - load_tiles_q4_0, VDR_Q4_0_Q8_1_MMQ, vec_dot_q4_0_q8_1_mul_mat> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); -} - -template -static void ggml_mul_mat_q4_0_q8_1_cuda( - const void * vx, const void * vy, scalar_t * dst, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, cudaStream_t stream) { - - int mmq_x = MMQ_X_Q4_0; - int mmq_y = MMQ_Y_Q4_0; - int nwarps = NWARPS_Q4_0; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (ncols_y + mmq_x - 1) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - const bool need_check = false; - mul_mat_q4_0<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } else { - const bool need_check = true; - mul_mat_q4_0<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } -} - -#if defined(USE_ROCM) -#define MMQ_X_Q4_1 64 -#define MMQ_Y_Q4_1 128 -#define NWARPS_Q4_1 8 -#else -#define MMQ_X_Q4_1 4 -#define MMQ_Y_Q4_1 32 -#define NWARPS_Q4_1 4 -#endif - -template static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF*NWARPS_Q4_1, 2) -#endif -mul_mat_q4_1( - const void * __restrict__ vx, const void * __restrict__ vy, scalar_t * __restrict__ dst, - const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { - const int mmq_x = MMQ_X_Q4_1; - const int mmq_y = MMQ_Y_Q4_1; - const int nwarps = NWARPS_Q4_1; - - mul_mat_q, - load_tiles_q4_1, VDR_Q4_1_Q8_1_MMQ, vec_dot_q4_1_q8_1_mul_mat> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); -} - -template -static void ggml_mul_mat_q4_1_q8_1_cuda( - const void * vx, const void * vy, scalar_t * dst, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, cudaStream_t stream) { - - int mmq_x = MMQ_X_Q4_1; - int mmq_y = MMQ_Y_Q4_1; - int nwarps = NWARPS_Q4_1; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (ncols_y + mmq_x - 1) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - const bool need_check = false; - mul_mat_q4_1<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } else { - const bool need_check = true; - mul_mat_q4_1<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } -} - -#if defined(USE_ROCM) -#define MMQ_X_Q5_0 64 -#define MMQ_Y_Q5_0 128 -#define NWARPS_Q5_0 8 -#else -#define MMQ_X_Q5_0 4 -#define MMQ_Y_Q5_0 32 -#define NWARPS_Q5_0 4 -#endif - -template static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF*NWARPS_Q5_0, 2) -#endif -mul_mat_q5_0( - const void * __restrict__ vx, const void * __restrict__ vy, scalar_t * __restrict__ dst, - const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { - const int mmq_x = MMQ_X_Q5_0; - const int mmq_y = MMQ_Y_Q5_0; - const int nwarps = NWARPS_Q5_0; - - mul_mat_q, - load_tiles_q5_0, VDR_Q5_0_Q8_1_MMQ, vec_dot_q5_0_q8_1_mul_mat> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); -} - -template -static void ggml_mul_mat_q5_0_q8_1_cuda( - const void * vx, const void * vy, scalar_t * dst, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, cudaStream_t stream) { - - const int mmq_x = MMQ_X_Q5_0; - const int mmq_y = MMQ_Y_Q5_0; - const int nwarps = NWARPS_Q5_0; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (ncols_y + mmq_x - 1) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - const bool need_check = false; - mul_mat_q5_0<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } else { - const bool need_check = true; - mul_mat_q5_0<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } -} - -#if defined(USE_ROCM) -#define MMQ_X_Q5_1 64 -#define MMQ_Y_Q5_1 128 -#define NWARPS_Q5_1 8 -#else -#define MMQ_X_Q5_1 4 -#define MMQ_Y_Q5_1 32 -#define NWARPS_Q5_1 4 -#endif - -template static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF*NWARPS_Q5_1, 2) -#endif -mul_mat_q5_1( - const void * __restrict__ vx, const void * __restrict__ vy, scalar_t * __restrict__ dst, - const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { - const int mmq_x = MMQ_X_Q5_1; - const int mmq_y = MMQ_Y_Q5_1; - const int nwarps = NWARPS_Q5_1; - - mul_mat_q, - load_tiles_q5_1, VDR_Q5_1_Q8_1_MMQ, vec_dot_q5_1_q8_1_mul_mat> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); -} - -template -static void ggml_mul_mat_q5_1_q8_1_cuda( - const void * vx, const void * vy, scalar_t * dst, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, cudaStream_t stream) { - const int mmq_x = MMQ_X_Q5_1; - const int mmq_y = MMQ_Y_Q5_1; - const int nwarps = NWARPS_Q5_1; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (ncols_y + mmq_x - 1) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - const bool need_check = false; - mul_mat_q5_1<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } else { - const bool need_check = true; - mul_mat_q5_1<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } -} - -#if defined(USE_ROCM) -#define MMQ_X_Q8_0 64 -#define MMQ_Y_Q8_0 128 -#define NWARPS_Q8_0 8 -#else -#define MMQ_X_Q8_0 4 -#define MMQ_Y_Q8_0 32 -#define NWARPS_Q8_0 4 -#endif - -template static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF*NWARPS_Q8_0, 2) -#endif -mul_mat_q8_0( - const void * __restrict__ vx, const void * __restrict__ vy, scalar_t * __restrict__ dst, - const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { - const int mmq_x = MMQ_X_Q8_0; - const int mmq_y = MMQ_Y_Q8_0; - const int nwarps = NWARPS_Q8_0; - - mul_mat_q, - load_tiles_q8_0, VDR_Q8_0_Q8_1_MMQ, vec_dot_q8_0_q8_1_mul_mat> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); -} - -template -static void ggml_mul_mat_q8_0_q8_1_cuda( - const void * vx, const void * vy, scalar_t * dst, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, cudaStream_t stream) { - const int mmq_x = MMQ_X_Q8_0; - const int mmq_y = MMQ_Y_Q8_0; - const int nwarps = NWARPS_Q8_0; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (ncols_y + mmq_x - 1) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - const bool need_check = false; - mul_mat_q8_0<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } else { - const bool need_check = true; - mul_mat_q8_0<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } -} - -#if defined(USE_ROCM) -#define MMQ_X_Q2_K 64 -#define MMQ_Y_Q2_K 128 -#define NWARPS_Q2_K 8 -#else -#define MMQ_X_Q2_K 4 -#define MMQ_Y_Q2_K 32 -#define NWARPS_Q2_K 4 -#endif - -template static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF*NWARPS_Q2_K, 2) -#endif -mul_mat_q2_K( - const void * __restrict__ vx, const void * __restrict__ vy, scalar_t * __restrict__ dst, - const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { - const int mmq_x = MMQ_X_Q2_K; - const int mmq_y = MMQ_Y_Q2_K; - const int nwarps = NWARPS_Q2_K; - - mul_mat_q, - load_tiles_q2_K, VDR_Q2_K_Q8_1_MMQ, vec_dot_q2_K_q8_1_mul_mat> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); -} - -template -static void ggml_mul_mat_q2_K_q8_1_cuda( - const void * vx, const void * vy, scalar_t * dst, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, cudaStream_t stream) { - const int mmq_x = MMQ_X_Q2_K; - const int mmq_y = MMQ_Y_Q2_K; - const int nwarps = NWARPS_Q2_K; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (ncols_y + mmq_x - 1) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - const bool need_check = false; - mul_mat_q2_K<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } else { - const bool need_check = true; - mul_mat_q2_K<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } -} - -#if defined(USE_ROCM) -#define MMQ_X_Q3_K 64 -#define MMQ_Y_Q3_K 128 -#define NWARPS_Q3_K 8 -#else -#define MMQ_X_Q3_K 4 -#define MMQ_Y_Q3_K 32 -#define NWARPS_Q3_K 4 -#endif - -template static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF*NWARPS_Q3_K, 2) -#endif -mul_mat_q3_K( - const void * __restrict__ vx, const void * __restrict__ vy, scalar_t * __restrict__ dst, - const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { - - const int mmq_x = MMQ_X_Q3_K; - const int mmq_y = MMQ_Y_Q3_K; - const int nwarps = NWARPS_Q3_K; - - mul_mat_q, - load_tiles_q3_K, VDR_Q3_K_Q8_1_MMQ, vec_dot_q3_K_q8_1_mul_mat> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); -} - -template -static void ggml_mul_mat_q3_K_q8_1_cuda( - const void * vx, const void * vy, scalar_t * dst, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, cudaStream_t stream) { - - const int mmq_x = MMQ_X_Q3_K; - const int mmq_y = MMQ_Y_Q3_K; - const int nwarps = NWARPS_Q3_K; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (ncols_y + mmq_x - 1) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - const bool need_check = false; - mul_mat_q3_K<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } else { - const bool need_check = true; - mul_mat_q3_K<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } -} - -#if defined(USE_ROCM) -#define MMQ_X_Q4_K 64 -#define MMQ_Y_Q4_K 128 -#define NWARPS_Q4_K 8 -#else -#define MMQ_X_Q4_K 4 -#define MMQ_Y_Q4_K 32 -#define NWARPS_Q4_K 4 -#endif - -template static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF*NWARPS_Q4_K, 2) -#endif -mul_mat_q4_K( - const void * __restrict__ vx, const void * __restrict__ vy, scalar_t * __restrict__ dst, - const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { - const int mmq_x = MMQ_X_Q4_K; - const int mmq_y = MMQ_Y_Q4_K; - const int nwarps = NWARPS_Q4_K; - - mul_mat_q, - load_tiles_q4_K, VDR_Q4_K_Q8_1_MMQ, vec_dot_q4_K_q8_1_mul_mat> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); -} - -template -static void ggml_mul_mat_q4_K_q8_1_cuda( - const void * vx, const void * vy, scalar_t * dst, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, cudaStream_t stream) { - const int mmq_x = MMQ_X_Q4_K; - const int mmq_y = MMQ_Y_Q4_K; - const int nwarps = NWARPS_Q4_K; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (ncols_y + mmq_x - 1) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - const bool need_check = false; - mul_mat_q4_K<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } else { - const bool need_check = true; - mul_mat_q4_K<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } -} - -#if defined(USE_ROCM) -#define MMQ_X_Q5_K 64 -#define MMQ_Y_Q5_K 128 -#define NWARPS_Q5_K 8 -#else -#define MMQ_X_Q5_K 4 -#define MMQ_Y_Q5_K 32 -#define NWARPS_Q5_K 4 -#endif - -template static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF*NWARPS_Q5_K, 2) -#endif -mul_mat_q5_K( - const void * __restrict__ vx, const void * __restrict__ vy, scalar_t * __restrict__ dst, - const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { - const int mmq_x = MMQ_X_Q5_K; - const int mmq_y = MMQ_Y_Q5_K; - const int nwarps = NWARPS_Q5_K; - - mul_mat_q, - load_tiles_q5_K, VDR_Q5_K_Q8_1_MMQ, vec_dot_q5_K_q8_1_mul_mat> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); -} - -template -static void ggml_mul_mat_q5_K_q8_1_cuda( - const void * vx, const void * vy, scalar_t * dst, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, cudaStream_t stream) { - - const int mmq_x = MMQ_X_Q5_K; - const int mmq_y = MMQ_Y_Q5_K; - const int nwarps = NWARPS_Q5_K; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (ncols_y + mmq_x - 1) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - const bool need_check = false; - mul_mat_q5_K<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } else { - const bool need_check = true; - mul_mat_q5_K<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } -} - -#if defined(USE_ROCM) -#define MMQ_X_Q6_K 64 -#define MMQ_Y_Q6_K 128 -#define NWARPS_Q6_K 8 -#else -#define MMQ_X_Q6_K 4 -#define MMQ_Y_Q6_K 32 -#define NWARPS_Q6_K 4 -#endif - -template static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF*NWARPS_Q6_K, 2) -#endif -mul_mat_q6_K( - const void * __restrict__ vx, const void * __restrict__ vy, scalar_t * __restrict__ dst, - const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { - const int mmq_x = MMQ_X_Q6_K; - const int mmq_y = MMQ_Y_Q6_K; - const int nwarps = NWARPS_Q6_K; - - mul_mat_q, - load_tiles_q6_K, VDR_Q6_K_Q8_1_MMQ, vec_dot_q6_K_q8_1_mul_mat> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); -} - -template -static void ggml_mul_mat_q6_K_q8_1_cuda( - const void * vx, const void * vy, scalar_t * dst, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, cudaStream_t stream) { - const int mmq_x = MMQ_X_Q6_K; - const int mmq_y = MMQ_Y_Q6_K; - const int nwarps = NWARPS_Q6_K; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (ncols_y + mmq_x - 1) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - const bool need_check = false; - mul_mat_q6_K<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } else { - const bool need_check = true; - mul_mat_q6_K<<>> - (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); - } -} diff --git a/csrc/libtorch_stable/quantization/gguf/mmvq.cuh b/csrc/libtorch_stable/quantization/gguf/mmvq.cuh deleted file mode 100644 index e27bec7af5b7..000000000000 --- a/csrc/libtorch_stable/quantization/gguf/mmvq.cuh +++ /dev/null @@ -1,212 +0,0 @@ -// copied and adapted from https://github.com/ggerganov/llama.cpp/blob/b2899/ggml-cuda/mmvq.cu -template -static __global__ void mul_mat_vec_q(const void * __restrict__ vx, const void * __restrict__ vy, scalar_t * __restrict__ dst, const int ncols, const int nrows, const int nvecs) { - const auto row = blockIdx.x*blockDim.y + threadIdx.y; - const auto vec = blockIdx.y; - - if (row >= nrows || vec >= nvecs) { - return; - } - - const int blocks_per_row = ncols / qk; - const int blocks_per_warp = vdr * WARP_SIZE / qi; - const int nrows_y = (ncols + 512 - 1) / 512 * 512; - - - // partial sum for each thread - float tmp = 0.0f; - - const block_q_t * x = (const block_q_t *) vx; - const block_q8_1 * y = (const block_q8_1 *) vy; - - for (auto i = threadIdx.x / (qi/vdr); i < blocks_per_row; i += blocks_per_warp) { - const int ibx = row*blocks_per_row + i; // x block index - - const int iby = vec*(nrows_y/QK8_1) + i * (qk/QK8_1); // y block index that aligns with ibx - - const int iqs = vdr * (threadIdx.x % (qi/vdr)); // x block quant index when casting the quants to int - - tmp += vec_dot_q_cuda(&x[ibx], &y[iby], iqs); - } - - // sum up partial sums and write back result -#pragma unroll - for (int mask = WARP_SIZE/2; mask > 0; mask >>= 1) { - tmp += VLLM_SHFL_XOR_SYNC(tmp, mask); - } - - if (threadIdx.x == 0) { - dst[vec*nrows + row] = tmp; - } -} - -template -static void mul_mat_vec_q4_0_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_q4_1_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_q5_0_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_q5_1_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_q8_0_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_q2_K_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_q3_K_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_q4_K_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_q5_K_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_q6_K_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_iq2_xxs_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_iq2_xs_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_iq2_s_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_iq3_xxs_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_iq1_s_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_iq1_m_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_iq4_nl_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_iq4_xs_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} - -template -static void mul_mat_vec_iq3_s_q8_1_cuda(const void * vx, const void * vy, scalar_t * dst, const int ncols, const int nrows, const int nvecs, cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, nvecs, 1); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - mul_mat_vec_q - <<>>(vx, vy, dst, ncols, nrows, nvecs); -} diff --git a/csrc/libtorch_stable/quantization/gguf/moe.cuh b/csrc/libtorch_stable/quantization/gguf/moe.cuh deleted file mode 100644 index a2f9f46c8f89..000000000000 --- a/csrc/libtorch_stable/quantization/gguf/moe.cuh +++ /dev/null @@ -1,739 +0,0 @@ -#include - -/* Adapted from ./csrc/quantization/gguf/mmq.cuh - based on ./vllm/model_executor/layers/fused_moe/experts/triton_moe.py */ -template -static __device__ __forceinline__ void moe_q( - const void* __restrict__ vx, const void* __restrict__ vy, - scalar_t* __restrict__ dst, const int* __restrict__ sorted_token_ids, - const int* __restrict__ expert_ids, - const int* __restrict__ num_tokens_post_padded, const int exp_stride, - const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, - const int nrows_dst, const int top_k) { - const int blocks_per_row_x = ncols_x / qk; - const int blocks_per_col_y = nrows_y / QK8_1; - const int blocks_per_warp = WARP_SIZE_GGUF / qi; - - const int ncols_dst = ncols_y * top_k; - - const auto row_dst_0 = blockIdx.x * mmq_y; - const int& row_x_0 = row_dst_0; - - const auto col_dst_0 = blockIdx.y * mmq_x; - - int token_offs[mmq_x / nwarps]; - for (int i = 0; i < mmq_x; i += nwarps) { - token_offs[i / nwarps] = sorted_token_ids[col_dst_0 + threadIdx.y + i]; - } - - const int exp_idx = expert_ids[blockIdx.y]; - if (exp_idx > 255 || exp_idx < 0) return; - if (blockIdx.y * mmq_x > num_tokens_post_padded[0]) return; - - const block_q_t* x = (const block_q_t*)((char*)vx + exp_idx * exp_stride); - const block_q8_1* y = (const block_q8_1*)(vy); - - int* tile_x_ql = nullptr; - half2* tile_x_dm = nullptr; - int* tile_x_qh = nullptr; - int* tile_x_sc = nullptr; - - allocate_tiles(&tile_x_ql, &tile_x_dm, &tile_x_qh, &tile_x_sc); - - __shared__ int tile_y_qs[mmq_x * WARP_SIZE_GGUF]; - __shared__ half2 tile_y_ds[mmq_x * WARP_SIZE_GGUF / QI8_1]; - - float sum[mmq_y / WARP_SIZE_GGUF][mmq_x / nwarps] = {{0.0f}}; - - for (int ib0 = 0; ib0 < blocks_per_row_x; ib0 += blocks_per_warp) { - load_tiles(x + row_x_0 * blocks_per_row_x + ib0, tile_x_ql, tile_x_dm, - tile_x_qh, tile_x_sc, threadIdx.y, nrows_x - row_x_0 - 1, - threadIdx.x, blocks_per_row_x); - - const int n_per_r = ((qk * blocks_per_warp) / qr); -#pragma unroll - for (int ir = 0; ir < qr && ib0 * qk + ir * n_per_r < ncols_x; ++ir) { - const auto kqs = ir * WARP_SIZE_GGUF + threadIdx.x; - const int kbxd = kqs / QI8_1; - -#pragma unroll - for (int i = 0; i < mmq_x; i += nwarps) { - const int col_y_eff = token_offs[i / nwarps] / top_k; - const int block_x = ib0 * (qk / QK8_1) + kbxd; - if (col_y_eff < ncols_y && block_x < blocks_per_col_y) { - const block_q8_1* by0 = &y[col_y_eff * blocks_per_col_y + block_x]; - const int index_y = - (threadIdx.y + i) * WARP_SIZE_GGUF + kqs % WARP_SIZE_GGUF; - tile_y_qs[index_y] = - get_int_from_int8_aligned(by0->qs, threadIdx.x % QI8_1); - } - } - - if (threadIdx.x < n_per_r / QK8_1) { - const auto kby = threadIdx.x % (WARP_SIZE_GGUF / QI8_1); - const int col_y_eff = token_offs[threadIdx.y] / top_k; - const int block_x = - ib0 * (qk / QK8_1) + ir * (WARP_SIZE_GGUF / QI8_1) + kby; - - if (col_y_eff < ncols_y && block_x < blocks_per_col_y) { - const half2* dsi_src = &y[col_y_eff * blocks_per_col_y + block_x].ds; - half2* dsi_dst = - &tile_y_ds[threadIdx.y * (WARP_SIZE_GGUF / QI8_1) + kby]; - - if (need_sum) { - *dsi_dst = *dsi_src; - } else { - float* dfi_dst = (float*)dsi_dst; - *dfi_dst = __low2float(*dsi_src); - } - } - } - __syncthreads(); - - // #pragma unroll // unrolling this loop causes too much register pressure - for (int k = ir * WARP_SIZE_GGUF / qr; k < (ir + 1) * WARP_SIZE_GGUF / qr; - k += vdr) { -#pragma unroll - for (int j = 0; j < mmq_x; j += nwarps) { -#pragma unroll - for (int i = 0; i < mmq_y; i += WARP_SIZE_GGUF) { - sum[i / WARP_SIZE_GGUF][j / nwarps] += - vec_dot(tile_x_ql, tile_x_dm, tile_x_qh, tile_x_sc, tile_y_qs, - tile_y_ds, threadIdx.x + i, threadIdx.y + j, k); - } - } - } - __syncthreads(); - } - } - -#pragma unroll - for (int j = 0; j < mmq_x; j += nwarps) { - const int col_dst = token_offs[j / nwarps]; - if (col_dst >= ncols_dst) { - return; - } - -#pragma unroll - for (int i = 0; i < mmq_y; i += WARP_SIZE_GGUF) { - const auto row_dst = row_dst_0 + threadIdx.x + i; - if (row_dst >= nrows_dst) { - continue; - } - dst[col_dst * nrows_dst + row_dst] = sum[i / WARP_SIZE_GGUF][j / nwarps]; - } - } -} - -#if defined(USE_ROCM) - #define MOE_X_Q4_0 8 - #define MOE_Y_Q4_0 128 - #define NWARPS_Q4_0 8 -#else - #define MOE_X_Q4_0 4 - #define MOE_Y_Q4_0 32 - #define NWARPS_Q4_0 4 -#endif - -template -static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF* NWARPS_Q4_0, 2) -#endif - moe_q4_0(const void* __restrict__ vx, const void* __restrict__ vy, - scalar_t* __restrict__ dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, - const int top_k) { - const int mmq_x = MOE_X_Q4_0; - const int mmq_y = MOE_Y_Q4_0; - const int nwarps = NWARPS_Q4_0; - - moe_q, load_tiles_q4_0, - VDR_Q4_0_Q8_1_MMQ, vec_dot_q4_0_q8_1_mul_mat>( - vx, vy, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); -} - -template -static void ggml_moe_q4_0_q8_1_cuda( - const void* inp, const void* w, scalar_t* dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, const int top_k, - const int tokens_post_padded, cudaStream_t stream) { - int mmq_x = MOE_X_Q4_0; - int mmq_y = MOE_Y_Q4_0; - int nwarps = NWARPS_Q4_0; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (tokens_post_padded) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - constexpr bool need_check = false; - moe_q4_0<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } else { - constexpr bool need_check = true; - moe_q4_0<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } -} - -#if defined(USE_ROCM) - #define MOE_X_Q4_1 8 - #define MOE_Y_Q4_1 128 - #define NWARPS_Q4_1 8 -#else - #define MOE_X_Q4_1 4 - #define MOE_Y_Q4_1 32 - #define NWARPS_Q4_1 4 -#endif - -template -static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF* NWARPS_Q4_1, 2) -#endif - moe_q4_1(const void* __restrict__ vx, const void* __restrict__ vy, - scalar_t* __restrict__ dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, - const int top_k) { - const int mmq_x = MOE_X_Q4_1; - const int mmq_y = MOE_Y_Q4_1; - const int nwarps = NWARPS_Q4_1; - - moe_q, load_tiles_q4_1, - VDR_Q4_1_Q8_1_MMQ, vec_dot_q4_1_q8_1_mul_mat>( - vx, vy, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); -} - -template -static void ggml_moe_q4_1_q8_1_cuda( - const void* inp, const void* w, scalar_t* dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, const int top_k, - const int tokens_post_padded, cudaStream_t stream) { - int mmq_x = MOE_X_Q4_1; - int mmq_y = MOE_Y_Q4_1; - int nwarps = NWARPS_Q4_1; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (tokens_post_padded) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - constexpr bool need_check = false; - moe_q4_1<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } else { - constexpr bool need_check = true; - moe_q4_1<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } -} - -#if defined(USE_ROCM) - #define MOE_X_Q5_0 8 - #define MOE_Y_Q5_0 128 - #define NWARPS_Q5_0 8 -#else - #define MOE_X_Q5_0 4 - #define MOE_Y_Q5_0 32 - #define NWARPS_Q5_0 4 -#endif - -template -static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF* NWARPS_Q5_0, 2) -#endif - moe_q5_0(const void* __restrict__ vx, const void* __restrict__ vy, - scalar_t* __restrict__ dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, - const int top_k) { - const int mmq_x = MOE_X_Q5_0; - const int mmq_y = MOE_Y_Q5_0; - const int nwarps = NWARPS_Q5_0; - - moe_q, load_tiles_q5_0, - VDR_Q5_0_Q8_1_MMQ, vec_dot_q5_0_q8_1_mul_mat>( - vx, vy, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); -} - -template -static void ggml_moe_q5_0_q8_1_cuda( - const void* inp, const void* w, scalar_t* dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, const int top_k, - const int tokens_post_padded, cudaStream_t stream) { - const int mmq_x = MOE_X_Q5_0; - const int mmq_y = MOE_Y_Q5_0; - const int nwarps = NWARPS_Q5_0; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (tokens_post_padded) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - constexpr bool need_check = false; - moe_q5_0<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } else { - constexpr bool need_check = true; - moe_q5_0<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } -} - -#if defined(USE_ROCM) - #define MOE_X_Q5_1 8 - #define MOE_Y_Q5_1 128 - #define NWARPS_Q5_1 8 -#else - #define MOE_X_Q5_1 4 - #define MOE_Y_Q5_1 32 - #define NWARPS_Q5_1 4 -#endif - -template -static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF* NWARPS_Q5_1, 2) -#endif - moe_q5_1(const void* __restrict__ vx, const void* __restrict__ vy, - scalar_t* __restrict__ dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, - const int top_k) { - const int mmq_x = MOE_X_Q5_1; - const int mmq_y = MOE_Y_Q5_1; - const int nwarps = NWARPS_Q5_1; - - moe_q, load_tiles_q5_1, - VDR_Q5_1_Q8_1_MMQ, vec_dot_q5_1_q8_1_mul_mat>( - vx, vy, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); -} - -template -static void ggml_moe_q5_1_q8_1_cuda( - const void* inp, const void* w, scalar_t* dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, const int top_k, - const int tokens_post_padded, cudaStream_t stream) { - const int mmq_x = MOE_X_Q5_1; - const int mmq_y = MOE_Y_Q5_1; - const int nwarps = NWARPS_Q5_1; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (tokens_post_padded) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - constexpr bool need_check = false; - moe_q5_1<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } else { - constexpr bool need_check = true; - moe_q5_1<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } -} - -#if defined(USE_ROCM) - #define MOE_X_Q8_0 8 - #define MOE_Y_Q8_0 128 - #define NWARPS_Q8_0 8 -#else - #define MOE_X_Q8_0 4 - #define MOE_Y_Q8_0 32 - #define NWARPS_Q8_0 4 -#endif - -template -static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF* NWARPS_Q8_0, 2) -#endif - moe_q8_0(const void* __restrict__ vx, const void* __restrict__ vy, - scalar_t* __restrict__ dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, - const int top_k) { - const int mmq_x = MOE_X_Q8_0; - const int mmq_y = MOE_Y_Q8_0; - const int nwarps = NWARPS_Q8_0; - - moe_q, load_tiles_q8_0, - VDR_Q8_0_Q8_1_MMQ, vec_dot_q8_0_q8_1_mul_mat>( - vx, vy, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); -} - -template -static void ggml_moe_q8_0_q8_1_cuda( - const void* inp, const void* w, scalar_t* dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, const int top_k, - const int tokens_post_padded, cudaStream_t stream) { - const int mmq_x = MOE_X_Q8_0; - const int mmq_y = MOE_Y_Q8_0; - const int nwarps = NWARPS_Q8_0; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (tokens_post_padded) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - constexpr bool need_check = false; - moe_q8_0<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } else { - constexpr bool need_check = true; - moe_q8_0<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } -} - -#if defined(USE_ROCM) - #define MOE_X_Q2_K 8 - #define MOE_Y_Q2_K 128 - #define NWARPS_Q2_K 8 -#else - #define MOE_X_Q2_K 4 - #define MOE_Y_Q2_K 32 - #define NWARPS_Q2_K 4 -#endif - -template -static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF* NWARPS_Q2_K, 2) -#endif - moe_q2_K(const void* __restrict__ vx, const void* __restrict__ vy, - scalar_t* __restrict__ dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, - const int top_k) { - const int mmq_x = MOE_X_Q2_K; - const int mmq_y = MOE_Y_Q2_K; - const int nwarps = NWARPS_Q2_K; - - moe_q, load_tiles_q2_K, - VDR_Q2_K_Q8_1_MMQ, vec_dot_q2_K_q8_1_mul_mat>( - vx, vy, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); -} - -template -static void ggml_moe_q2_K_q8_1_cuda( - const void* inp, const void* w, scalar_t* dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, const int top_k, - const int tokens_post_padded, cudaStream_t stream) { - const int mmq_x = MOE_X_Q2_K; - const int mmq_y = MOE_Y_Q2_K; - const int nwarps = NWARPS_Q2_K; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (tokens_post_padded) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - constexpr bool need_check = false; - moe_q2_K<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } else { - constexpr bool need_check = true; - moe_q2_K<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } -} - -#if defined(USE_ROCM) - #define MOE_X_Q3_K 8 - #define MOE_Y_Q3_K 128 - #define NWARPS_Q3_K 8 -#else - #define MOE_X_Q3_K 4 - #define MOE_Y_Q3_K 32 - #define NWARPS_Q3_K 4 -#endif - -template -static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF* NWARPS_Q3_K, 2) -#endif - moe_q3_K(const void* __restrict__ vx, const void* __restrict__ vy, - scalar_t* __restrict__ dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, - const int top_k) { - - const int mmq_x = MOE_X_Q3_K; - const int mmq_y = MOE_Y_Q3_K; - const int nwarps = NWARPS_Q3_K; - - moe_q, load_tiles_q3_K, - VDR_Q3_K_Q8_1_MMQ, vec_dot_q3_K_q8_1_mul_mat>( - vx, vy, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); -} -template -static void ggml_moe_q3_K_q8_1_cuda( - const void* inp, const void* w, scalar_t* dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, const int top_k, - const int tokens_post_padded, cudaStream_t stream) { - const int mmq_x = MOE_X_Q3_K; - const int mmq_y = MOE_Y_Q3_K; - const int nwarps = NWARPS_Q3_K; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (tokens_post_padded) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - constexpr bool need_check = false; - moe_q3_K<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } else { - constexpr bool need_check = true; - moe_q3_K<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } -} - -#if defined(USE_ROCM) - #define MOE_X_Q4_K 8 - #define MOE_Y_Q4_K 128 - #define NWARPS_Q4_K 8 -#else - #define MOE_X_Q4_K 4 - #define MOE_Y_Q4_K 32 - #define NWARPS_Q4_K 4 -#endif - -template -static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF* NWARPS_Q4_K, 2) -#endif - moe_q4_K(const void* __restrict__ vx, const void* __restrict__ vy, - scalar_t* __restrict__ dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, - const int top_k) { - const int mmq_x = MOE_X_Q4_K; - const int mmq_y = MOE_Y_Q4_K; - const int nwarps = NWARPS_Q4_K; - - moe_q, load_tiles_q4_K, - VDR_Q4_K_Q8_1_MMQ, vec_dot_q4_K_q8_1_mul_mat>( - vx, vy, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); -} - -template -static void ggml_moe_q4_K_q8_1_cuda( - const void* inp, const void* w, scalar_t* dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, const int top_k, - const int tokens_post_padded, cudaStream_t stream) { - const int mmq_x = MOE_X_Q4_K; - const int mmq_y = MOE_Y_Q4_K; - const int nwarps = NWARPS_Q4_K; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (tokens_post_padded) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - constexpr bool need_check = false; - moe_q4_K<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } else { - constexpr bool need_check = true; - moe_q4_K<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } -} - -#if defined(USE_ROCM) - #define MOE_X_Q5_K 8 - #define MOE_Y_Q5_K 128 - #define NWARPS_Q5_K 8 -#else - #define MOE_X_Q5_K 4 - #define MOE_Y_Q5_K 32 - #define NWARPS_Q5_K 4 -#endif - -template -static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF* NWARPS_Q5_K, 2) -#endif - moe_q5_K(const void* __restrict__ vx, const void* __restrict__ vy, - scalar_t* __restrict__ dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, - const int top_k) { - const int mmq_x = MOE_X_Q5_K; - const int mmq_y = MOE_Y_Q5_K; - const int nwarps = NWARPS_Q5_K; - - moe_q, load_tiles_q5_K, - VDR_Q5_K_Q8_1_MMQ, vec_dot_q5_K_q8_1_mul_mat>( - vx, vy, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); -} - -template -static void ggml_moe_q5_K_q8_1_cuda( - const void* inp, const void* w, scalar_t* dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, const int top_k, - const int tokens_post_padded, cudaStream_t stream) { - const int mmq_x = MOE_X_Q5_K; - const int mmq_y = MOE_Y_Q5_K; - const int nwarps = NWARPS_Q5_K; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (tokens_post_padded) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - constexpr bool need_check = false; - moe_q5_K<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } else { - constexpr bool need_check = true; - moe_q5_K<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } -} - -#if defined(USE_ROCM) - #define MOE_X_Q6_K 8 - #define MOE_Y_Q6_K 128 - #define NWARPS_Q6_K 8 -#else - #define MOE_X_Q6_K 4 - #define MOE_Y_Q6_K 32 - #define NWARPS_Q6_K 4 -#endif - -template -static __global__ void -#if defined(USE_ROCM) -__launch_bounds__(WARP_SIZE_GGUF* NWARPS_Q6_K, 2) -#endif - moe_q6_K(const void* __restrict__ vx, const void* __restrict__ vy, - scalar_t* __restrict__ dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, - const int top_k) { - const int mmq_x = MOE_X_Q6_K; - const int mmq_y = MOE_Y_Q6_K; - const int nwarps = NWARPS_Q6_K; - - moe_q, load_tiles_q6_K, - VDR_Q6_K_Q8_1_MMQ, vec_dot_q6_K_q8_1_mul_mat>( - vx, vy, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); -} - -template -static void ggml_moe_q6_K_q8_1_cuda( - const void* inp, const void* w, scalar_t* dst, const int* sorted_token_ids, - const int* expert_ids, const int* num_tokens_post_padded, - const int exp_stride, const int ncols_x, const int nrows_x, - const int ncols_y, const int nrows_y, const int nrows_dst, const int top_k, - const int tokens_post_padded, cudaStream_t stream) { - const int mmq_x = MOE_X_Q6_K; - const int mmq_y = MOE_Y_Q6_K; - const int nwarps = NWARPS_Q6_K; - - const int block_num_x = (nrows_x + mmq_y - 1) / mmq_y; - const int block_num_y = (tokens_post_padded) / mmq_x; - const dim3 block_nums(block_num_x, block_num_y, 1); - const dim3 block_dims(WARP_SIZE_GGUF, nwarps, 1); - - if (nrows_x % mmq_y == 0) { - constexpr bool need_check = false; - moe_q6_K<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } else { - constexpr bool need_check = true; - moe_q6_K<<>>( - w, inp, dst, sorted_token_ids, expert_ids, num_tokens_post_padded, - exp_stride, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst, top_k); - } -} diff --git a/csrc/libtorch_stable/quantization/gguf/moe_vec.cuh b/csrc/libtorch_stable/quantization/gguf/moe_vec.cuh deleted file mode 100644 index 60f65a1bfdcb..000000000000 --- a/csrc/libtorch_stable/quantization/gguf/moe_vec.cuh +++ /dev/null @@ -1,338 +0,0 @@ -// copied and adapted from -// https://github.com/ggerganov/llama.cpp/blob/b2899/ggml-cuda/mmvq.cu -template -static __global__ void moe_vec_q(const void* __restrict__ vx, - const void* __restrict__ vy, - scalar_t* __restrict__ dst, - const int* topk_ids, const int topk, - const int ncols, const int nrows, - const int token_stride) { - const auto row = blockIdx.x * blockDim.y + threadIdx.y; - - const auto token = blockIdx.z / topk; - const auto expert = (topk_ids)[blockIdx.z]; - - if (row >= nrows) { - return; - } - - const int blocks_per_row = ncols / qk; - const int blocks_per_warp = vdr * WARP_SIZE / qi; - - // partial sum for each thread - float tmp = 0.0f; - - const block_q_t* x = ((const block_q_t*)vx) + expert * nrows * blocks_per_row; - const block_q8_1* y = - (const block_q8_1*)(((const int*)vy) + token * token_stride); - - for (auto i = threadIdx.x / (qi / vdr); i < blocks_per_row; - i += blocks_per_warp) { - const int ibx = row * blocks_per_row + i; // x block index - - const int iby = i * (qk / QK8_1); // y block index that aligns with ibx - - const int iqs = - vdr * - (threadIdx.x % - (qi / vdr)); // x block quant index when casting the quants to int - - tmp += vec_dot_q_cuda(&x[ibx], &y[iby], iqs); - } - - // sum up partial sums and write back result -#pragma unroll - for (int mask = WARP_SIZE / 2; mask > 0; mask >>= 1) { - tmp += VLLM_SHFL_XOR_SYNC(tmp, mask); - } - - if (threadIdx.x == 0) { - dst[blockIdx.z * nrows + row] = tmp; - } -} - -template -static void moe_vec_q4_0_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q<<>>( - vx, vy, dst, topk_ids, top_k, ncols, nrows, token_stride); -} - -template -static void moe_vec_q4_1_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q<<>>( - vx, vy, dst, topk_ids, top_k, ncols, nrows, token_stride); -} - -template -static void moe_vec_q5_0_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q<<>>( - vx, vy, dst, topk_ids, top_k, ncols, nrows, token_stride); -} - -template -static void moe_vec_q5_1_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q<<>>( - vx, vy, dst, topk_ids, top_k, ncols, nrows, token_stride); -} - -template -static void moe_vec_q8_0_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q<<>>( - vx, vy, dst, topk_ids, top_k, ncols, nrows, token_stride); -} - -template -static void moe_vec_q2_K_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q<<>>( - vx, vy, dst, topk_ids, top_k, ncols, nrows, token_stride); -} - -template -static void moe_vec_q3_K_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q<<>>( - vx, vy, dst, topk_ids, top_k, ncols, nrows, token_stride); -} - -template -static void moe_vec_q4_K_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q<<>>( - vx, vy, dst, topk_ids, top_k, ncols, nrows, token_stride); -} - -template -static void moe_vec_q5_K_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q<<>>( - vx, vy, dst, topk_ids, top_k, ncols, nrows, token_stride); -} - -template -static void moe_vec_q6_K_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q<<>>( - vx, vy, dst, topk_ids, top_k, ncols, nrows, token_stride); -} - -template -static void moe_vec_iq2_xxs_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q - <<>>(vx, vy, dst, topk_ids, top_k, - ncols, nrows, token_stride); -} - -template -static void moe_vec_iq2_xs_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q - <<>>(vx, vy, dst, topk_ids, top_k, - ncols, nrows, token_stride); -} - -template -static void moe_vec_iq2_s_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q - <<>>(vx, vy, dst, topk_ids, top_k, - ncols, nrows, token_stride); -} - -template -static void moe_vec_iq3_xxs_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q - <<>>(vx, vy, dst, topk_ids, top_k, - ncols, nrows, token_stride); -} - -template -static void moe_vec_iq1_s_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q - <<>>(vx, vy, dst, topk_ids, top_k, - ncols, nrows, token_stride); -} - -template -static void moe_vec_iq1_m_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q - <<>>(vx, vy, dst, topk_ids, top_k, - ncols, nrows, token_stride); -} - -template -static void moe_vec_iq4_nl_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q<<>>( - vx, vy, dst, topk_ids, top_k, ncols, nrows, token_stride); -} - -template -static void moe_vec_iq4_xs_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q - <<>>(vx, vy, dst, topk_ids, top_k, - ncols, nrows, token_stride); -} - -template -static void moe_vec_iq3_s_q8_1_cuda(const void* vx, const void* vy, - scalar_t* dst, const int* topk_ids, - const int top_k, const int tokens, - const int ncols, const int nrows, - const int token_stride, - cudaStream_t stream) { - const int block_num_y = (nrows + GGML_CUDA_MMV_Y - 1) / GGML_CUDA_MMV_Y; - const dim3 block_nums(block_num_y, 1, tokens * top_k); - const dim3 block_dims(WARP_SIZE, GGML_CUDA_MMV_Y, 1); - moe_vec_q - <<>>(vx, vy, dst, topk_ids, top_k, - ncols, nrows, token_stride); -} diff --git a/csrc/libtorch_stable/quantization/gguf/vecdotq.cuh b/csrc/libtorch_stable/quantization/gguf/vecdotq.cuh deleted file mode 100644 index d0d4c74ed379..000000000000 --- a/csrc/libtorch_stable/quantization/gguf/vecdotq.cuh +++ /dev/null @@ -1,1812 +0,0 @@ -// copied and adapted from https://github.com/ggerganov/llama.cpp/blob/b2899/ggml-cuda/vecdotq.cuh -// and https://github.com/ggerganov/llama.cpp/blob/b2899/ggml-cuda/mmq.cu -static __device__ __forceinline__ int get_int_b2(const void * x, const int & i32) { - const uint16_t * x16 = (const uint16_t *) x; // assume at least 2 byte alignment - - int x32 = x16[2*i32 + 0] << 0; - x32 |= x16[2*i32 + 1] << 16; - - return x32; -} - -static __device__ __forceinline__ int get_int_b4(const void * x, const int & i32) { - return ((const int *) x)[i32]; // assume at least 4 byte alignment -} - -static __device__ __forceinline__ int get_int_from_int8(const int8_t * x8, const int & i32) { - const uint16_t * x16 = (const uint16_t *) (x8 + sizeof(int) * i32); // assume at least 2 byte alignment - int x32 = 0; - x32 |= x16[0] << 0; - x32 |= x16[1] << 16; - return x32; -} - -static __device__ __forceinline__ int get_int_from_uint8(const uint8_t * x8, const int & i32) { - const uint16_t * x16 = (const uint16_t *) (x8 + sizeof(int) * i32); // assume at least 2 byte alignment - int x32 = 0; - x32 |= x16[0] << 0; - x32 |= x16[1] << 16; - return x32; -} - -static __device__ __forceinline__ int get_int_from_int8_aligned(const int8_t * x8, const int & i32) { - return *((const int *) (x8 + sizeof(int) * i32)); // assume at least 4 byte alignment -} - -static __device__ __forceinline__ int get_int_from_uint8_aligned(const uint8_t * x8, const int & i32) { - return *((const int *) (x8 + sizeof(int) * i32)); // assume at least 4 byte alignment -} - -// VDR = vec dot ratio, how many contiguous integers each thread processes when the vec dot kernel is called -// MMVQ = mul_mat_vec_q, MMQ = mul_mat_q - -#define VDR_Q4_0_Q8_1_MMVQ 2 -#define VDR_Q4_0_Q8_1_MMQ 4 - -template static __device__ __forceinline__ float vec_dot_q4_0_q8_1_impl( - const int * v, const int * u, const float & d4, const half2 & ds8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - int sumi = 0; - -#pragma unroll - for (int i = 0; i < vdr; ++i) { - const int vi0 = (v[i] >> 0) & 0x0F0F0F0F; - const int vi1 = (v[i] >> 4) & 0x0F0F0F0F; - - // SIMD dot product of quantized values - sumi = __dp4a(vi0, u[2*i+0], sumi); - sumi = __dp4a(vi1, u[2*i+1], sumi); - } - - const float2 ds8f = __half22float2(ds8); - - // second part effectively subtracts 8 from each quant value - return d4 * (sumi * ds8f.x - (8*vdr/QI4_0) * ds8f.y); -#endif -} - -#define VDR_Q4_1_Q8_1_MMVQ 2 -#define VDR_Q4_1_Q8_1_MMQ 4 - -template static __device__ __forceinline__ float vec_dot_q4_1_q8_1_impl( - const int * v, const int * u, const half2 & dm4, const half2 & ds8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - int sumi = 0; - -#pragma unroll - for (int i = 0; i < vdr; ++i) { - const int vi0 = (v[i] >> 0) & 0x0F0F0F0F; - const int vi1 = (v[i] >> 4) & 0x0F0F0F0F; - - // SIMD dot product of quantized values - sumi = __dp4a(vi0, u[2*i+0], sumi); - sumi = __dp4a(vi1, u[2*i+1], sumi); - } - - const float2 tmp = __half22float2(__hmul2(dm4, ds8)); - const float d4d8 = tmp.x; - const float m4s8 = tmp.y; - - // scale second part of sum by QI8_1/(vdr * QR4_1) to compensate for multiple threads adding it - return sumi * d4d8 + m4s8 / (QI8_1 / (vdr * QR4_1)); -#endif -} - -#define VDR_Q5_0_Q8_1_MMVQ 2 -#define VDR_Q5_0_Q8_1_MMQ 4 - -template static __device__ __forceinline__ float vec_dot_q5_0_q8_1_impl( - const int * vl, const int * vh, const int * u, const float & d5, const half2 & ds8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - int sumi = 0; - -#pragma unroll - for (int i = 0; i < vdr; ++i) { - int vi0 = (vl[i] >> 0) & 0x0F0F0F0F; // lower 4 qs bits, still need qh as 5th bits - vi0 |= (vh[i] << 4) & 0x00000010; // 0 -> 4 - vi0 |= (vh[i] << 11) & 0x00001000; // 1 -> 12 - vi0 |= (vh[i] << 18) & 0x00100000; // 2 -> 20 - vi0 |= (vh[i] << 25) & 0x10000000; // 3 -> 28 - sumi = __dp4a(vi0, u[2*i+0], sumi); // SIMD dot product of quantized values - - int vi1 = (vl[i] >> 4) & 0x0F0F0F0F; // upper 4 qs bits, still need qh as 5th bits - vi1 |= (vh[i] >> 12) & 0x00000010; // 16 -> 4 - vi1 |= (vh[i] >> 5) & 0x00001000; // 17 -> 12 - vi1 |= (vh[i] << 2) & 0x00100000; // 18 -> 20 - vi1 |= (vh[i] << 9) & 0x10000000; // 19 -> 28 - sumi = __dp4a(vi1, u[2*i+1], sumi); // SIMD dot product of quantized values - } - - const float2 ds8f = __half22float2(ds8); - - // second part effectively subtracts 16 from each quant value - return d5 * (sumi * ds8f.x - (16*vdr/QI5_0) * ds8f.y); -#endif -} - - -#define VDR_Q5_1_Q8_1_MMVQ 2 -#define VDR_Q5_1_Q8_1_MMQ 4 - -template static __device__ __forceinline__ float vec_dot_q5_1_q8_1_impl( - const int * vl, const int * vh, const int * u, const half2 & dm5, const half2 & ds8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - int sumi = 0; - -#pragma unroll - for (int i = 0; i < vdr; ++i) { - int vi0 = (vl[i] >> 0) & 0x0F0F0F0F; // lower 4 qs bits, still need qh as 5th bits - vi0 |= (vh[i] << 4) & 0x00000010; // 0 -> 4 - vi0 |= (vh[i] << 11) & 0x00001000; // 1 -> 12 - vi0 |= (vh[i] << 18) & 0x00100000; // 2 -> 20 - vi0 |= (vh[i] << 25) & 0x10000000; // 3 -> 28 - sumi = __dp4a(vi0, u[2*i+0], sumi); // SIMD dot product of quantized values - - int vi1 = (vl[i] >> 4) & 0x0F0F0F0F; // upper 4 qs bits, still need qh as 5th bits - vi1 |= (vh[i] >> 12) & 0x00000010; // 16 -> 4 - vi1 |= (vh[i] >> 5) & 0x00001000; // 17 -> 12 - vi1 |= (vh[i] << 2) & 0x00100000; // 18 -> 20 - vi1 |= (vh[i] << 9) & 0x10000000; // 19 -> 28 - sumi = __dp4a(vi1, u[2*i+1], sumi); // SIMD dot product of quantized values - } - - const float2 tmp = __half22float2(__hmul2(dm5, ds8)); - const float d5d8 = tmp.x; - const float m5s8 = tmp.y; - - // scale second part of sum by QI5_1 / vdr to compensate for multiple threads adding it - return sumi*d5d8 + m5s8 / (QI5_1 / vdr); -#endif -} - -#define VDR_Q8_0_Q8_1_MMVQ 2 -#define VDR_Q8_0_Q8_1_MMQ 8 - -template static __device__ __forceinline__ float vec_dot_q8_0_q8_1_impl( - const int * v, const int * u, const float & d8_0, const float & d8_1) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - int sumi = 0; - -#pragma unroll - for (int i = 0; i < vdr; ++i) { - // SIMD dot product of quantized values - sumi = __dp4a(v[i], u[i], sumi); - } - return d8_0*d8_1 * sumi; -#endif -} - -template static __device__ __forceinline__ float vec_dot_q8_1_q8_1_impl( - const int * v, const int * u, const half2 & dm8, const half2 & ds8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - - int sumi = 0; - -#pragma unroll - for (int i = 0; i < vdr; ++i) { - // SIMD dot product of quantized values - sumi = __dp4a(v[i], u[i], sumi); - } - - const float2 tmp = __half22float2(__hmul2(dm8, ds8)); - const float d8d8 = tmp.x; - const float m8s8 = tmp.y; - - // scale second part of sum by QI8_1/ vdr to compensate for multiple threads adding it - return sumi*d8d8 + m8s8 / (QI8_1 / vdr); -#endif -} - -#define VDR_Q2_K_Q8_1_MMVQ 1 -#define VDR_Q2_K_Q8_1_MMQ 2 - -// contiguous v/x values -static __device__ __forceinline__ float vec_dot_q2_K_q8_1_impl_mmvq( - const int & v, const int * __restrict__ u, const uint8_t * __restrict__ scales, - const half2 & dm2, const float * __restrict__ d8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - float sumf_d = 0.0f; - float sumf_m = 0.0f; - -#pragma unroll - for (int i = 0; i < QR2_K; ++i) { - const int sc = scales[2*i]; - - const int vi = (v >> (2*i)) & 0x03030303; - - sumf_d += d8[i] * (__dp4a(vi, u[i], 0) * (sc & 0xF)); // SIMD dot product - - // fill int with 4x m - int m = sc >> 4; - m |= m << 8; - m |= m << 16; - sumf_m += d8[i] * __dp4a(m, u[i], 0); // multiply constant q2_K part with sum of q8_1 values - } - - const float2 dm2f = __half22float2(dm2); - - return dm2f.x*sumf_d - dm2f.y*sumf_m; -#endif -} - -static __device__ __forceinline__ float vec_dot_q2_K_q8_1_impl_mmq( - const int * __restrict__ v, const int * __restrict__ u, const uint8_t * __restrict__ scales, - const half2 & dm2, const float & d8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - int sumi_d = 0; - int sumi_m = 0; - -#pragma unroll - for (int i0 = 0; i0 < QI8_1; i0 += QI8_1/2) { - int sumi_d_sc = 0; - - const int sc = scales[i0 / (QI8_1/2)]; - - // fill int with 4x m - int m = sc >> 4; - m |= m << 8; - m |= m << 16; - -#pragma unroll - for (int i = i0; i < i0 + QI8_1/2; ++i) { - sumi_d_sc = __dp4a(v[i], u[i], sumi_d_sc); // SIMD dot product - sumi_m = __dp4a(m, u[i], sumi_m); // multiply sum of q8_1 values with m - } - - sumi_d += sumi_d_sc * (sc & 0xF); - } - - const float2 dm2f = __half22float2(dm2); - - return d8 * (dm2f.x*sumi_d - dm2f.y*sumi_m); -#endif -} - -#define VDR_Q3_K_Q8_1_MMVQ 1 -#define VDR_Q3_K_Q8_1_MMQ 2 - -// contiguous v/x values -static __device__ __forceinline__ float vec_dot_q3_K_q8_1_impl_mmvq( - const int & vl, const int & vh, const int * __restrict__ u, const uint8_t * __restrict__ scales, - const int & scale_offset, const float & d3, const float * __restrict__ d8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - - float sumf = 0.0f; - -#pragma unroll - for (int i = 0; i < QR3_K; ++i) { - const int isc = scale_offset + 2*i; - - const int isc_low = isc % (QK_K/32); - const int sc_shift_low = 4 * (isc / (QK_K/32)); - const int sc_low = (scales[isc_low] >> sc_shift_low) & 0xF; - - const int isc_high = isc % (QK_K/64); - const int sc_shift_high = 2 * (isc / (QK_K/64)); - const int sc_high = ((scales[(QK_K/32) + isc_high] >> sc_shift_high) & 3) << 4; - - const int sc = (sc_low | sc_high) - 32; - - const int vil = (vl >> (2*i)) & 0x03030303; - - const int vih = ((vh >> i) << 2) & 0x04040404; - - const int vi = __vsubss4(vil, vih); - - sumf += d8[i] * (__dp4a(vi, u[i], 0) * sc); // SIMD dot product - } - - return d3 * sumf; -#endif -} - -static __device__ __forceinline__ float vec_dot_q3_K_q8_1_impl_mmq( - const int * __restrict__ v, const int * __restrict__ u, const int8_t * __restrict__ scales, - const float & d3, const float & d8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - int sumi = 0; - -#pragma unroll - for (int i0 = 0; i0 < QR3_K*VDR_Q3_K_Q8_1_MMQ; i0 += QI8_1/2) { - int sumi_sc = 0; - - for (int i = i0; i < i0 + QI8_1/2; ++i) { - sumi_sc = __dp4a(v[i], u[i], sumi_sc); // SIMD dot product - } - - sumi += sumi_sc * scales[i0 / (QI8_1/2)]; - } - - return d3*d8 * sumi; -#endif -} - -#define VDR_Q4_K_Q8_1_MMVQ 2 -#define VDR_Q4_K_Q8_1_MMQ 8 - -// contiguous v/x values -static __device__ __forceinline__ float vec_dot_q4_K_q8_1_impl_vmmq( - const int * __restrict__ v, const int * __restrict__ u, const uint8_t * __restrict__ sc, - const uint8_t * __restrict__ m, const half2 & dm4, const float * __restrict__ d8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - - float sumf_d = 0.0f; - float sumf_m = 0.0f; - -#pragma unroll - for (int i = 0; i < QR4_K; ++i) { - const int v0i = (v[0] >> (4*i)) & 0x0F0F0F0F; - const int v1i = (v[1] >> (4*i)) & 0x0F0F0F0F; - - const int dot1 = __dp4a(v1i, u[2*i+1], __dp4a(v0i, u[2*i+0], 0)); // SIMD dot product - const int dot2 = __dp4a(0x01010101, u[2*i+1], __dp4a(0x01010101, u[2*i+0], 0)); // sum of u - - sumf_d += d8[i] * (dot1 * sc[i]); - sumf_m += d8[i] * (dot2 * m[i]); // multiply constant part of q4_K with sum of q8_1 values - } - - const float2 dm4f = __half22float2(dm4); - return dm4f.x*sumf_d - dm4f.y*sumf_m; -#endif -} - -static __device__ __forceinline__ float vec_dot_q4_K_q8_1_impl_mmq( - const int * __restrict__ v, const int * __restrict__ u, const uint8_t * __restrict__ sc, - const uint8_t * __restrict__ m, const half2 & dm4, const half2 * __restrict__ ds8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - float sumf_d = 0.0f; - float sumf_m = 0.0f; - -#pragma unroll - for (int i = 0; i < QR4_K*VDR_Q4_K_Q8_1_MMQ/QI8_1; ++i) { - int sumi_d = 0; - -#pragma unroll - for (int j = 0; j < QI8_1; ++j) { - sumi_d = __dp4a((v[j] >> (4*i)) & 0x0F0F0F0F, u[i*QI8_1 + j], sumi_d); // SIMD dot product - } - - const float2 ds8f = __half22float2(ds8[i]); - - sumf_d += ds8f.x * (sc[i] * sumi_d); - sumf_m += ds8f.y * m[i]; // sum of q8_1 block * q4_K min val - } - - const float2 dm4f = __half22float2(dm4); - - return dm4f.x*sumf_d - dm4f.y*sumf_m; -#endif -} - -#define VDR_Q5_K_Q8_1_MMVQ 2 -#define VDR_Q5_K_Q8_1_MMQ 8 - -static __device__ __forceinline__ float vec_dot_q5_K_q8_1_impl_vmmq( - const int * __restrict__ vl, const int * __restrict__ vh, const int * __restrict__ u, const uint8_t * __restrict__ sc, - const uint8_t * __restrict__ m, const half2 & dm5, const float * __restrict__ d8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - - float sumf_d = 0.0f; - float sumf_m = 0.0f; - -#pragma unroll - for (int i = 0; i < QR5_K; ++i) { - const int vl0i = (vl[0] >> (4*i)) & 0x0F0F0F0F; - const int vl1i = (vl[1] >> (4*i)) & 0x0F0F0F0F; - - const int vh0i = ((vh[0] >> i) << 4) & 0x10101010; - const int vh1i = ((vh[1] >> i) << 4) & 0x10101010; - - const int v0i = vl0i | vh0i; - const int v1i = vl1i | vh1i; - - const int dot1 = __dp4a(v0i, u[2*i+0], __dp4a(v1i, u[2*i+1], 0)); // SIMD dot product - const int dot2 = __dp4a(0x01010101, u[2*i+0], __dp4a(0x01010101, u[2*i+1], 0)); // sum of u - - sumf_d += d8[i] * (dot1 * sc[i]); - sumf_m += d8[i] * (dot2 * m[i]); - } - - const float2 dm5f = __half22float2(dm5); - return dm5f.x*sumf_d - dm5f.y*sumf_m; -#endif -} - -static __device__ __forceinline__ float vec_dot_q5_K_q8_1_impl_mmq( - const int * __restrict__ v, const int * __restrict__ u, const uint8_t * __restrict__ sc, - const uint8_t * __restrict__ m, const half2 & dm4, const half2 * __restrict__ ds8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - float sumf_d = 0.0f; - float sumf_m = 0.0f; - -#pragma unroll - for (int i = 0; i < QR5_K*VDR_Q5_K_Q8_1_MMQ/QI8_1; ++i) { - int sumi_d = 0; - -#pragma unroll - for (int j = 0; j < QI8_1; ++j) { - sumi_d = __dp4a(v[i*QI8_1 + j], u[i*QI8_1 + j], sumi_d); // SIMD dot product - } - - const float2 ds8f = __half22float2(ds8[i]); - - sumf_d += ds8f.x * (sc[i] * sumi_d); - sumf_m += ds8f.y * m[i]; // sum of q8_1 block * q4_K min val - } - - const float2 dm4f = __half22float2(dm4); - - return dm4f.x*sumf_d - dm4f.y*sumf_m; -#endif -} - -#define VDR_Q6_K_Q8_1_MMVQ 1 -#define VDR_Q6_K_Q8_1_MMQ 8 - -// contiguous v/x values -static __device__ __forceinline__ float vec_dot_q6_K_q8_1_impl_mmvq( - const int & vl, const int & vh, const int * __restrict__ u, const int8_t * __restrict__ scales, - const float & d, const float * __restrict__ d8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - float sumf = 0.0f; - -#pragma unroll - for (int i = 0; i < QR6_K; ++i) { - const int sc = scales[4*i]; - const int vil = (vl >> (4*i)) & 0x0F0F0F0F; - const int vih = ((vh >> (4*i)) << 4) & 0x30303030; - const int vi = __vsubss4((vil | vih), 0x20202020); // vi = (vil | vih) - 32 - - sumf += d8[i] * (__dp4a(vi, u[i], 0) * sc); // SIMD dot product - } - - return d*sumf; -#endif -} - -static __device__ __forceinline__ float vec_dot_q6_K_q8_1_impl_mmq( - const int * __restrict__ v, const int * __restrict__ u, const int8_t * __restrict__ sc, - const float & d6, const float * __restrict__ d8) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - float sumf_d = 0.0f; - -#pragma unroll - for (int i0 = 0; i0 < VDR_Q6_K_Q8_1_MMQ; i0 += 4) { - int2 sumi_d = {0, 0}; // 2 q6_K scales per q8_1 scale - -#pragma unroll - for (int i = i0; i < i0 + 2; ++i) { - sumi_d.x = __dp4a(v[2*i+0], u[2*i+0], sumi_d.x); // SIMD dot product - sumi_d.x = __dp4a(v[2*i+1], u[2*i+1], sumi_d.x); // SIMD dot product - - sumi_d.y = __dp4a(v[2*i+4], u[2*i+4], sumi_d.y); // SIMD dot product - sumi_d.y = __dp4a(v[2*i+5], u[2*i+5], sumi_d.y); // SIMD dot product - } - - sumf_d += d8[i0/4] * (sc[i0/2+0]*sumi_d.x + sc[i0/2+1]*sumi_d.y); - } - - return d6 * sumf_d; -#endif -} - -static __device__ __forceinline__ float vec_dot_q4_0_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { - - const block_q4_0 * bq4_0 = (const block_q4_0 *) vbq; - - int v[VDR_Q4_0_Q8_1_MMVQ]; - int u[2*VDR_Q4_0_Q8_1_MMVQ]; - -#pragma unroll - for (int i = 0; i < VDR_Q4_0_Q8_1_MMVQ; ++i) { - v[i] = get_int_from_uint8(bq4_0->qs, iqs + i); - u[2*i+0] = get_int_from_int8_aligned(bq8_1->qs, iqs + i); - u[2*i+1] = get_int_from_int8_aligned(bq8_1->qs, iqs + i + QI4_0); - } - - return vec_dot_q4_0_q8_1_impl(v, u, __half2float(bq4_0->d), bq8_1->ds); -} - -template static __device__ __forceinline__ void allocate_tiles_q4_0(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { - __shared__ int tile_x_qs[mmq_y * (WARP_SIZE_GGUF) + mmq_y]; - __shared__ float tile_x_d[mmq_y * (WARP_SIZE_GGUF/QI4_0) + mmq_y/QI4_0]; - *x_ql = tile_x_qs; - *x_dm = (half2 *) tile_x_d; -} - -template static __device__ __forceinline__ void load_tiles_q4_0( - const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, - int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { - const int kbx = k / QI4_0; - const int kqsx = k % QI4_0; - - const block_q4_0 * bx0 = (const block_q4_0 *) vx; - float * x_dmf = (float *) x_dm; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { - int i = i0 + i_offset; - if (need_check) { - i = min(i, i_max); - } - const block_q4_0 * bxi = bx0 + i*blocks_per_row + kbx; - x_ql[i * (WARP_SIZE_GGUF + 1) + k] = get_int_from_uint8(bxi->qs, kqsx); - // x_dmf[i * (WARP_SIZE_GGUF/QI4_0) + i / QI4_0 + kbx] = bxi->d; - } - - const int blocks_per_tile_x_row = WARP_SIZE_GGUF / QI4_0; - const int kbxd = k % blocks_per_tile_x_row; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI4_0) { - int i = i0 + i_offset * QI4_0 + k / blocks_per_tile_x_row; - if (need_check) { - i = min(i, i_max); - } - const block_q4_0 * bxi = bx0 + i*blocks_per_row + kbxd; - x_dmf[i * (WARP_SIZE_GGUF/QI4_0) + i / QI4_0 + kbxd] = __half2float(bxi->d); - } -} - -static __device__ __forceinline__ float vec_dot_q4_0_q8_1_mul_mat( - const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, - const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { - (void)x_qh; (void)x_sc; - - const int kyqs = k % (QI8_1/2) + QI8_1 * (k / (QI8_1/2)); - const float * x_dmf = (const float *) x_dm; - - int u[2*VDR_Q4_0_Q8_1_MMQ]; - -#pragma unroll - for (int l = 0; l < VDR_Q4_0_Q8_1_MMQ; ++l) { - u[2*l+0] = y_qs[j * WARP_SIZE_GGUF + (kyqs + l) % WARP_SIZE_GGUF]; - u[2*l+1] = y_qs[j * WARP_SIZE_GGUF + (kyqs + l + QI4_0) % WARP_SIZE_GGUF]; - } - - return vec_dot_q4_0_q8_1_impl - (&x_ql[i * (WARP_SIZE_GGUF + 1) + k], u, x_dmf[i * (WARP_SIZE_GGUF/QI4_0) + i/QI4_0 + k/QI4_0], - y_ds[j * (WARP_SIZE_GGUF/QI8_1) + (2*k/QI8_1) % (WARP_SIZE_GGUF/QI8_1)]); -} - -static __device__ __forceinline__ float vec_dot_q4_1_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { - - const block_q4_1 * bq4_1 = (const block_q4_1 *) vbq; - - int v[VDR_Q4_1_Q8_1_MMVQ]; - int u[2*VDR_Q4_1_Q8_1_MMVQ]; - -#pragma unroll - for (int i = 0; i < VDR_Q4_1_Q8_1_MMVQ; ++i) { - v[i] = get_int_from_uint8_aligned(bq4_1->qs, iqs + i); - u[2*i+0] = get_int_from_int8_aligned(bq8_1->qs, iqs + i); - u[2*i+1] = get_int_from_int8_aligned(bq8_1->qs, iqs + i + QI4_1); - } - - return vec_dot_q4_1_q8_1_impl(v, u, bq4_1->dm, bq8_1->ds); -} - -template static __device__ __forceinline__ void allocate_tiles_q4_1(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { - __shared__ int tile_x_qs[mmq_y * (WARP_SIZE_GGUF) + + mmq_y]; - __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE_GGUF/QI4_1) + mmq_y/QI4_1]; - *x_ql = tile_x_qs; - *x_dm = tile_x_dm; -} - -template static __device__ __forceinline__ void load_tiles_q4_1( - const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, - int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { - const int kbx = k / QI4_1; - const int kqsx = k % QI4_1; - - const block_q4_1 * bx0 = (const block_q4_1 *) vx; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { - int i = i0 + i_offset; - if (need_check) { - i = min(i, i_max); - } - const block_q4_1 * bxi = bx0 + i*blocks_per_row + kbx; - x_ql[i * (WARP_SIZE_GGUF + 1) + k] = get_int_from_uint8_aligned(bxi->qs, kqsx); - } - - const int blocks_per_tile_x_row = WARP_SIZE_GGUF / QI4_1; - const int kbxd = k % blocks_per_tile_x_row; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI4_1) { - int i = i0 + i_offset * QI4_1 + k / blocks_per_tile_x_row; - if (need_check) { - i = min(i, i_max); - } - const block_q4_1 * bxi = bx0 + i*blocks_per_row + kbxd; - x_dm[i * (WARP_SIZE_GGUF/QI4_1) + i / QI4_1 + kbxd] = bxi->dm; - } -} - -static __device__ __forceinline__ float vec_dot_q4_1_q8_1_mul_mat( - const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, - const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { - const int kyqs = k % (QI8_1/2) + QI8_1 * (k / (QI8_1/2)); - - int u[2*VDR_Q4_1_Q8_1_MMQ]; - -#pragma unroll - for (int l = 0; l < VDR_Q4_1_Q8_1_MMQ; ++l) { - u[2*l+0] = y_qs[j * WARP_SIZE_GGUF + (kyqs + l) % WARP_SIZE_GGUF]; - u[2*l+1] = y_qs[j * WARP_SIZE_GGUF + (kyqs + l + QI4_1) % WARP_SIZE_GGUF]; - } - - return vec_dot_q4_1_q8_1_impl - (&x_ql[i * (WARP_SIZE_GGUF + 1) + k], u, x_dm[i * (WARP_SIZE_GGUF/QI4_1) + i/QI4_1 + k/QI4_1], - y_ds[j * (WARP_SIZE_GGUF/QI8_1) + (2*k/QI8_1) % (WARP_SIZE_GGUF/QI8_1)]); -} - -static __device__ __forceinline__ float vec_dot_q5_0_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { - - const block_q5_0 * bq5_0 = (const block_q5_0 *) vbq; - - int vl[VDR_Q5_0_Q8_1_MMVQ]; - int vh[VDR_Q5_0_Q8_1_MMVQ]; - int u[2*VDR_Q5_0_Q8_1_MMVQ]; - -#pragma unroll - for (int i = 0; i < VDR_Q5_0_Q8_1_MMVQ; ++i) { - vl[i] = get_int_from_uint8(bq5_0->qs, iqs + i); - vh[i] = get_int_from_uint8(bq5_0->qh, 0) >> (4 * (iqs + i)); - u[2*i+0] = get_int_from_int8_aligned(bq8_1->qs, iqs + i); - u[2*i+1] = get_int_from_int8_aligned(bq8_1->qs, iqs + i + QI5_0); - } - - return vec_dot_q5_0_q8_1_impl(vl, vh, u, __half2float(bq5_0->d), bq8_1->ds); -} - -template static __device__ __forceinline__ void allocate_tiles_q5_0(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { - __shared__ int tile_x_ql[mmq_y * (2*WARP_SIZE_GGUF) + mmq_y]; - __shared__ float tile_x_d[mmq_y * (WARP_SIZE_GGUF/QI5_0) + mmq_y/QI5_0]; - - *x_ql = tile_x_ql; - *x_dm = (half2 *) tile_x_d; -} - -template static __device__ __forceinline__ void load_tiles_q5_0( - const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, - int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { - const int kbx = k / QI5_0; - const int kqsx = k % QI5_0; - - const block_q5_0 * bx0 = (const block_q5_0 *) vx; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { - int i = i0 + i_offset; - - if (need_check) { - i = min(i, i_max); - } - const block_q5_0 * bxi = bx0 + i*blocks_per_row + kbx; - const int ql = get_int_from_uint8(bxi->qs, kqsx); - const int qh = get_int_from_uint8(bxi->qh, 0) >> (4 * (k % QI5_0)); - - int qs0 = (ql >> 0) & 0x0F0F0F0F; - qs0 |= (qh << 4) & 0x00000010; // 0 -> 4 - qs0 |= (qh << 11) & 0x00001000; // 1 -> 12 - qs0 |= (qh << 18) & 0x00100000; // 2 -> 20 - qs0 |= (qh << 25) & 0x10000000; // 3 -> 28 - qs0 = __vsubss4(qs0, 0x10101010); // subtract 16 - - x_ql[i * (2*WARP_SIZE_GGUF + 1) + 2*k+0] = qs0; - - int qs1 = (ql >> 4) & 0x0F0F0F0F; - qs1 |= (qh >> 12) & 0x00000010; // 16 -> 4 - qs1 |= (qh >> 5) & 0x00001000; // 17 -> 12 - qs1 |= (qh << 2) & 0x00100000; // 18 -> 20 - qs1 |= (qh << 9) & 0x10000000; // 19 -> 28 - qs1 = __vsubss4(qs1, 0x10101010); // subtract 16 - - x_ql[i * (2*WARP_SIZE_GGUF + 1) + 2*k+1] = qs1; - } - - const int blocks_per_tile_x_row = WARP_SIZE_GGUF / QI5_0; - const int kbxd = k % blocks_per_tile_x_row; - float * x_dmf = (float *) x_dm; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI5_0) { - int i = i0 + i_offset * QI5_0 + k / blocks_per_tile_x_row; - - if (need_check) { - i = min(i, i_max); - } - - const block_q5_0 * bxi = bx0 + i*blocks_per_row + kbxd; - x_dmf[i * (WARP_SIZE_GGUF/QI5_0) + i / QI5_0 + kbxd] = __half2float(bxi->d); - } -} - -static __device__ __forceinline__ float vec_dot_q5_0_q8_1_mul_mat( - const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, - const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { - const int kyqs = k % (QI8_1/2) + QI8_1 * (k / (QI8_1/2)); - const int index_bx = i * (WARP_SIZE_GGUF/QI5_0) + i/QI5_0 + k/QI5_0; - const float * x_dmf = (const float *) x_dm; - const float * y_df = (const float *) y_ds; - - int u[2*VDR_Q5_0_Q8_1_MMQ]; - -#pragma unroll - for (int l = 0; l < VDR_Q5_0_Q8_1_MMQ; ++l) { - u[2*l+0] = y_qs[j * WARP_SIZE_GGUF + (kyqs + l) % WARP_SIZE_GGUF]; - u[2*l+1] = y_qs[j * WARP_SIZE_GGUF + (kyqs + l + QI5_0) % WARP_SIZE_GGUF]; - } - - return vec_dot_q8_0_q8_1_impl - (&x_ql[i * (2*WARP_SIZE_GGUF + 1) + 2 * k], u, x_dmf[index_bx], y_df[j * (WARP_SIZE_GGUF/QI8_1) + (2*k/QI8_1) % (WARP_SIZE_GGUF/QI8_1)]); -} - -static __device__ __forceinline__ float vec_dot_q5_1_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { - - const block_q5_1 * bq5_1 = (const block_q5_1 *) vbq; - - int vl[VDR_Q5_1_Q8_1_MMVQ]; - int vh[VDR_Q5_1_Q8_1_MMVQ]; - int u[2*VDR_Q5_1_Q8_1_MMVQ]; - -#pragma unroll - for (int i = 0; i < VDR_Q5_1_Q8_1_MMVQ; ++i) { - vl[i] = get_int_from_uint8_aligned(bq5_1->qs, iqs + i); - vh[i] = get_int_from_uint8_aligned(bq5_1->qh, 0) >> (4 * (iqs + i)); - u[2*i+0] = get_int_from_int8_aligned(bq8_1->qs, iqs + i); - u[2*i+1] = get_int_from_int8_aligned(bq8_1->qs, iqs + i + QI5_1); - } - - return vec_dot_q5_1_q8_1_impl(vl, vh, u, bq5_1->dm, bq8_1->ds); -} - -template static __device__ __forceinline__ void allocate_tiles_q5_1(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { - __shared__ int tile_x_ql[mmq_y * (2*WARP_SIZE_GGUF) + mmq_y]; - __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE_GGUF/QI5_1) + mmq_y/QI5_1]; - - *x_ql = tile_x_ql; - *x_dm = tile_x_dm; -} - -template static __device__ __forceinline__ void load_tiles_q5_1( - const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, - int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { - const int kbx = k / QI5_1; - const int kqsx = k % QI5_1; - - const block_q5_1 * bx0 = (const block_q5_1 *) vx; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { - int i = i0 + i_offset; - - if (need_check) { - i = min(i, i_max); - } - - const block_q5_1 * bxi = bx0 + i*blocks_per_row + kbx; - - const int ql = get_int_from_uint8_aligned(bxi->qs, kqsx); - const int qh = get_int_from_uint8_aligned(bxi->qh, 0) >> (4 * (k % QI5_1)); - - int qs0 = (ql >> 0) & 0x0F0F0F0F; - qs0 |= (qh << 4) & 0x00000010; // 0 -> 4 - qs0 |= (qh << 11) & 0x00001000; // 1 -> 12 - qs0 |= (qh << 18) & 0x00100000; // 2 -> 20 - qs0 |= (qh << 25) & 0x10000000; // 3 -> 28 - - x_ql[i * (2*WARP_SIZE_GGUF + 1) + 2*k+0] = qs0; - - int qs1 = (ql >> 4) & 0x0F0F0F0F; - qs1 |= (qh >> 12) & 0x00000010; // 16 -> 4 - qs1 |= (qh >> 5) & 0x00001000; // 17 -> 12 - qs1 |= (qh << 2) & 0x00100000; // 18 -> 20 - qs1 |= (qh << 9) & 0x10000000; // 19 -> 28 - - x_ql[i * (2*WARP_SIZE_GGUF + 1) + 2*k+1] = qs1; - } - - const int blocks_per_tile_x_row = WARP_SIZE_GGUF / QI5_1; - const int kbxd = k % blocks_per_tile_x_row; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI5_1) { - int i = i0 + i_offset * QI5_1 + k / blocks_per_tile_x_row; - - if (need_check) { - i = min(i, i_max); - } - - const block_q5_1 * bxi = bx0 + i*blocks_per_row + kbxd; - - x_dm[i * (WARP_SIZE_GGUF/QI5_1) + i / QI5_1 + kbxd] = bxi->dm; - } -} - -static __device__ __forceinline__ float vec_dot_q5_1_q8_1_mul_mat( - const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, - const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { - const int kyqs = k % (QI8_1/2) + QI8_1 * (k / (QI8_1/2)); - const int index_bx = i * (WARP_SIZE_GGUF/QI5_1) + + i/QI5_1 + k/QI5_1; - - int u[2*VDR_Q5_1_Q8_1_MMQ]; - -#pragma unroll - for (int l = 0; l < VDR_Q5_1_Q8_1_MMQ; ++l) { - u[2*l+0] = y_qs[j * WARP_SIZE_GGUF + (kyqs + l) % WARP_SIZE_GGUF]; - u[2*l+1] = y_qs[j * WARP_SIZE_GGUF + (kyqs + l + QI5_1) % WARP_SIZE_GGUF]; - } - - return vec_dot_q8_1_q8_1_impl - (&x_ql[i * (2*WARP_SIZE_GGUF + 1) + 2 * k], u, x_dm[index_bx], y_ds[j * (WARP_SIZE_GGUF/QI8_1) + (2*k/QI8_1) % (WARP_SIZE_GGUF/QI8_1)]); -} - -static __device__ __forceinline__ float vec_dot_q8_0_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { - - const block_q8_0 * bq8_0 = (const block_q8_0 *) vbq; - - int v[VDR_Q8_0_Q8_1_MMVQ]; - int u[VDR_Q8_0_Q8_1_MMVQ]; - -#pragma unroll - for (int i = 0; i < VDR_Q8_0_Q8_1_MMVQ; ++i) { - v[i] = get_int_from_int8(bq8_0->qs, iqs + i); - u[i] = get_int_from_int8_aligned(bq8_1->qs, iqs + i); - } - - return vec_dot_q8_0_q8_1_impl(v, u, __half2float(bq8_0->d), __low2float(bq8_1->ds)); -} - -template static __device__ __forceinline__ void allocate_tiles_q8_0(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { - __shared__ int tile_x_qs[mmq_y * (WARP_SIZE_GGUF) + mmq_y]; - __shared__ float tile_x_d[mmq_y * (WARP_SIZE_GGUF/QI8_0) + mmq_y/QI8_0]; - - *x_ql = tile_x_qs; - *x_dm = (half2 *) tile_x_d; -} - -template static __device__ __forceinline__ void load_tiles_q8_0( - const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, - int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { - const int kbx = k / QI8_0; - const int kqsx = k % QI8_0; - float * x_dmf = (float *) x_dm; - - const block_q8_0 * bx0 = (const block_q8_0 *) vx; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { - int i = i0 + i_offset; - - if (need_check) { - i = min(i, i_max); - } - const block_q8_0 * bxi = bx0 + i*blocks_per_row + kbx; - x_ql[i * (WARP_SIZE_GGUF + 1) + k] = get_int_from_int8(bxi->qs, kqsx); - } - - const int blocks_per_tile_x_row = WARP_SIZE_GGUF / QI8_0; - const int kbxd = k % blocks_per_tile_x_row; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI8_0) { - int i = i0 + i_offset * QI8_0 + k / blocks_per_tile_x_row; - - if (need_check) { - i = min(i, i_max); - } - const block_q8_0 * bxi = bx0 + i*blocks_per_row + kbxd; - x_dmf[i * (WARP_SIZE_GGUF/QI8_0) + i / QI8_0 + kbxd] = __half2float(bxi->d); - } -} - -static __device__ __forceinline__ float vec_dot_q8_0_q8_1_mul_mat( - const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, - const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { - const float * x_dmf = (const float *) x_dm; - const float * y_df = (const float *) y_ds; - - return vec_dot_q8_0_q8_1_impl - (&x_ql[i * (WARP_SIZE_GGUF + 1) + k], &y_qs[j * WARP_SIZE_GGUF + k], x_dmf[i * (WARP_SIZE_GGUF/QI8_0) + i/QI8_0 + k/QI8_0], - y_df[j * (WARP_SIZE_GGUF/QI8_1) + k/QI8_1]); -} - -static __device__ __forceinline__ float vec_dot_q2_K_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { - - const block_q2_K * bq2_K = (const block_q2_K *) vbq; - - const int bq8_offset = QR2_K * (iqs / QI8_1); - const int scale_offset = iqs - iqs % QI8_1 + (iqs % QI8_1) / (QI8_1/2); - - const uint8_t * scales = bq2_K->scales + scale_offset; - - const int v = get_int_from_uint8_aligned(bq2_K->qs, iqs); - int u[QR2_K]; - float d8[QR2_K]; - -#pragma unroll - for (int i = 0; i < QR2_K; ++ i) { - u[i] = get_int_from_int8_aligned(bq8_1[bq8_offset + i].qs, iqs % QI8_1); - d8[i] = __low2float(bq8_1[bq8_offset + i].ds); - } - - return vec_dot_q2_K_q8_1_impl_mmvq(v, u, scales, bq2_K->dm, d8); -} - -template static __device__ __forceinline__ void allocate_tiles_q2_K(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { - __shared__ int tile_x_ql[mmq_y * (WARP_SIZE_GGUF) + mmq_y]; - __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE_GGUF/QI2_K) + mmq_y/QI2_K]; - __shared__ int tile_x_sc[mmq_y * (WARP_SIZE_GGUF/4) + mmq_y/4]; - - *x_ql = tile_x_ql; - *x_dm = tile_x_dm; - *x_sc = tile_x_sc; -} - -template static __device__ __forceinline__ void load_tiles_q2_K( - const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, - int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { - const int kbx = k / QI2_K; - const int kqsx = k % QI2_K; - - const block_q2_K * bx0 = (const block_q2_K *) vx; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { - int i = i0 + i_offset; - - if (need_check) { - i = min(i, i_max); - } - const block_q2_K * bxi = bx0 + i*blocks_per_row + kbx; - x_ql[i * (WARP_SIZE_GGUF + 1) + k] = get_int_from_uint8_aligned(bxi->qs, kqsx); - } - - const int blocks_per_tile_x_row = WARP_SIZE_GGUF / QI2_K; - const int kbxd = k % blocks_per_tile_x_row; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI2_K) { - int i = (i0 + i_offset * QI2_K + k / blocks_per_tile_x_row) % mmq_y; - - if (need_check) { - i = min(i, i_max); - } - const block_q2_K * bxi = bx0 + i*blocks_per_row + kbxd; - x_dm[i * (WARP_SIZE_GGUF/QI2_K) + i / QI2_K + kbxd] = bxi->dm; - } - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * 4) { - int i = i0 + i_offset * 4 + k / (WARP_SIZE_GGUF/4); - - if (need_check) { - i = min(i, i_max); - } - const block_q2_K * bxi = bx0 + i*blocks_per_row + (k % (WARP_SIZE_GGUF/4)) / (QI2_K/4); - x_sc[i * (WARP_SIZE_GGUF/4) + i / 4 + k % (WARP_SIZE_GGUF/4)] = get_int_from_uint8_aligned(bxi->scales, k % (QI2_K/4)); - } -} - -static __device__ __forceinline__ float vec_dot_q2_K_q8_1_mul_mat( - const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, - const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { - const int kbx = k / QI2_K; - const int ky = (k % QI2_K) * QR2_K; - const float * y_df = (const float *) y_ds; - - int v[QR2_K*VDR_Q2_K_Q8_1_MMQ]; - - const int kqsx = i * (WARP_SIZE_GGUF + 1) + kbx*QI2_K + (QI2_K/2) * (ky/(2*QI2_K)) + ky % (QI2_K/2); - const int shift = 2 * ((ky % (2*QI2_K)) / (QI2_K/2)); - -#pragma unroll - for (int l = 0; l < QR2_K*VDR_Q2_K_Q8_1_MMQ; ++l) { - v[l] = (x_ql[kqsx + l] >> shift) & 0x03030303; - } - - const uint8_t * scales = ((const uint8_t *) &x_sc[i * (WARP_SIZE_GGUF/4) + i/4 + kbx*4]) + ky/4; - - const int index_y = j * WARP_SIZE_GGUF + (QR2_K*k) % WARP_SIZE_GGUF; - return vec_dot_q2_K_q8_1_impl_mmq(v, &y_qs[index_y], scales, x_dm[i * (WARP_SIZE_GGUF/QI2_K) + i/QI2_K + kbx], y_df[index_y/QI8_1]); -} - -static __device__ __forceinline__ float vec_dot_q3_K_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { - - const block_q3_K * bq3_K = (const block_q3_K *) vbq; - - const int bq8_offset = QR3_K * (iqs / (QI3_K/2)); - const int scale_offset = iqs - iqs % QI8_1 + (iqs % QI8_1) / (QI8_1/2); - - const float d = __half2float(bq3_K->d); - - const int vl = get_int_from_uint8(bq3_K->qs, iqs); - - // invert the mask with ~ so that a 0/1 results in 4/0 being subtracted - const int vh = ~get_int_from_uint8(bq3_K->hmask, iqs % (QI3_K/2)) >> bq8_offset; - - int u[QR3_K]; - float d8[QR3_K]; - -#pragma unroll - for (int i = 0; i < QR3_K; ++i) { - u[i] = get_int_from_int8_aligned(bq8_1[bq8_offset + i].qs, iqs % QI8_1); - d8[i] = __low2float(bq8_1[bq8_offset + i].ds); - } - - return vec_dot_q3_K_q8_1_impl_mmvq(vl, vh, u, bq3_K->scales, scale_offset, d, d8); -} - -template static __device__ __forceinline__ void allocate_tiles_q3_K(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { - __shared__ int tile_x_ql[mmq_y * (WARP_SIZE_GGUF) + mmq_y]; - __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE_GGUF/QI3_K) + mmq_y/QI3_K]; - __shared__ int tile_x_qh[mmq_y * (WARP_SIZE_GGUF/2) + mmq_y/2]; - __shared__ int tile_x_sc[mmq_y * (WARP_SIZE_GGUF/4) + mmq_y/4]; - - *x_ql = tile_x_ql; - *x_dm = tile_x_dm; - *x_qh = tile_x_qh; - *x_sc = tile_x_sc; -} - -template static __device__ __forceinline__ void load_tiles_q3_K( - const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, - int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { - const int kbx = k / QI3_K; - const int kqsx = k % QI3_K; - - const block_q3_K * bx0 = (const block_q3_K *) vx; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { - int i = i0 + i_offset; - if (need_check) { - i = min(i, i_max); - } - const block_q3_K * bxi = bx0 + i*blocks_per_row + kbx; - x_ql[i * (WARP_SIZE_GGUF + 1) + k] = get_int_from_uint8(bxi->qs, kqsx); - } - - const int blocks_per_tile_x_row = WARP_SIZE_GGUF / QI3_K; - const int kbxd = k % blocks_per_tile_x_row; - float * x_dmf = (float *) x_dm; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI3_K) { - int i = (i0 + i_offset * QI3_K + k / blocks_per_tile_x_row) % mmq_y; - if (need_check) { - i = min(i, i_max); - } - const block_q3_K * bxi = bx0 + i*blocks_per_row + kbxd; - x_dmf[i * (WARP_SIZE_GGUF/QI3_K) + i / QI3_K + kbxd] = __half2float(bxi->d); - } - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * 2) { - int i = i0 + i_offset * 2 + k / (WARP_SIZE_GGUF/2); - if (need_check) { - i = min(i, i_max); - } - const block_q3_K * bxi = bx0 + i*blocks_per_row + (k % (WARP_SIZE_GGUF/2)) / (QI3_K/2); - // invert the mask with ~ so that a 0/1 results in 4/0 being subtracted - x_qh[i * (WARP_SIZE_GGUF/2) + i / 2 + k % (WARP_SIZE_GGUF/2)] = ~get_int_from_uint8(bxi->hmask, k % (QI3_K/2)); - } - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * 4) { - int i = i0 + i_offset * 4 + k / (WARP_SIZE_GGUF/4); - if (need_check) { - i = min(i, i_max); - } - const block_q3_K * bxi = bx0 + i*blocks_per_row + (k % (WARP_SIZE_GGUF/4)) / (QI3_K/4); - - const int ksc = k % (QI3_K/4); - - const int ksc_low = ksc % (QI3_K/8); - const int shift_low = 4 * (ksc / (QI3_K/8)); - const int sc_low = (get_int_from_uint8(bxi->scales, ksc_low) >> shift_low) & 0x0F0F0F0F; - - const int ksc_high = QI3_K/8; - const int shift_high = 2 * ksc; - const int sc_high = ((get_int_from_uint8(bxi->scales, ksc_high) >> shift_high) << 4) & 0x30303030; - - const int sc = __vsubss4(sc_low | sc_high, 0x20202020); - - x_sc[i * (WARP_SIZE_GGUF/4) + i / 4 + k % (WARP_SIZE_GGUF/4)] = sc; - } -} - -static __device__ __forceinline__ float vec_dot_q3_K_q8_1_mul_mat( - const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, - const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { - - const int kbx = k / QI3_K; - const int ky = (k % QI3_K) * QR3_K; - const float * x_dmf = (const float *) x_dm; - const float * y_df = (const float *) y_ds; - - const int8_t * scales = ((const int8_t *) (x_sc + i * (WARP_SIZE_GGUF/4) + i/4 + kbx*4)) + ky/4; - - int v[QR3_K*VDR_Q3_K_Q8_1_MMQ]; - -#pragma unroll - for (int l = 0; l < QR3_K*VDR_Q3_K_Q8_1_MMQ; ++l) { - const int kqsx = i * (WARP_SIZE_GGUF + 1) + kbx*QI3_K + (QI3_K/2) * (ky/(2*QI3_K)) + ky % (QI3_K/2); - const int shift = 2 * ((ky % 32) / 8); - const int vll = (x_ql[kqsx + l] >> shift) & 0x03030303; - - const int vh = x_qh[i * (WARP_SIZE_GGUF/2) + i/2 + kbx * (QI3_K/2) + (ky+l)%8] >> ((ky+l) / 8); - const int vlh = (vh << 2) & 0x04040404; - - v[l] = __vsubss4(vll, vlh); - } - - const int index_y = j * WARP_SIZE_GGUF + (k*QR3_K) % WARP_SIZE_GGUF; - return vec_dot_q3_K_q8_1_impl_mmq(v, &y_qs[index_y], scales, x_dmf[i * (WARP_SIZE_GGUF/QI3_K) + i/QI3_K + kbx], y_df[index_y/QI8_1]); -} - -static __device__ __forceinline__ float vec_dot_q4_K_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { - const block_q4_K * bq4_K = (const block_q4_K *) vbq; - - int v[2]; - int u[2*QR4_K]; - float d8[QR4_K]; - - // iqs is in 0,2..30. bq8_offset = iqs/4 -> bq8_offset = 0, 2, 4, 6 - const int bq8_offset = QR4_K * ((iqs/2) / (QI8_1/2)); - - // iqs = 0....3 -> bq8_offset = 0, want q4_offset = 0, 4, 8, 12 - // iqs = 4....7 -> bq8_offset = 2, want q4_offset = 32, 36, 40, 44 - // iqs = 8...11 -> bq8_offset = 4, want q4_offset = 64, 68, 72, 76 - // iqs = 12..15 -> bq8_offset = 6, want q4_offset = 96, 100, 104, 108 - - const int * q4 = (const int *)(bq4_K->qs + 16 * bq8_offset + 4 * ((iqs/2)%4)); - v[0] = q4[0]; - v[1] = q4[4]; - - const uint16_t * scales = (const uint16_t *)bq4_K->scales; - uint16_t aux[2]; - const int j = bq8_offset/2; - if (j < 2) { - aux[0] = scales[j+0] & 0x3f3f; - aux[1] = scales[j+2] & 0x3f3f; - } else { - aux[0] = ((scales[j+2] >> 0) & 0x0f0f) | ((scales[j-2] & 0xc0c0) >> 2); - aux[1] = ((scales[j+2] >> 4) & 0x0f0f) | ((scales[j-0] & 0xc0c0) >> 2); - } - const uint8_t * sc = (const uint8_t *)aux; - const uint8_t * m = sc + 2; - - for (int i = 0; i < QR4_K; ++i) { - const block_q8_1 * bq8i = bq8_1 + bq8_offset + i; - d8[i] = __low2float(bq8i->ds); - - const int * q8 = (const int *)bq8i->qs + ((iqs/2)%4); - u[2*i+0] = q8[0]; - u[2*i+1] = q8[4]; - } - - return vec_dot_q4_K_q8_1_impl_vmmq(v, u, sc, m, bq4_K->dm, d8); -} - -template static __device__ __forceinline__ void allocate_tiles_q4_K(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { - __shared__ int tile_x_ql[mmq_y * (WARP_SIZE_GGUF) + mmq_y]; - __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE_GGUF/QI4_K) + mmq_y/QI4_K]; - __shared__ int tile_x_sc[mmq_y * (WARP_SIZE_GGUF/8) + mmq_y/8]; - - *x_ql = tile_x_ql; - *x_dm = tile_x_dm; - *x_sc = tile_x_sc; -} - -template static __device__ __forceinline__ void load_tiles_q4_K( - const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, - int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { - const int kbx = k / QI4_K; // == 0 if QK_K == 256 - const int kqsx = k % QI4_K; // == k if QK_K == 256 - - const block_q4_K * bx0 = (const block_q4_K *) vx; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { - int i = i0 + i_offset; - - if (need_check) { - i = min(i, i_max); - } - const block_q4_K * bxi = bx0 + i*blocks_per_row + kbx; - x_ql[i * (WARP_SIZE_GGUF + 1) + k] = get_int_from_uint8_aligned(bxi->qs, kqsx); - } - - const int blocks_per_tile_x_row = WARP_SIZE_GGUF / QI4_K; // == 1 if QK_K == 256 - const int kbxd = k % blocks_per_tile_x_row; // == 0 if QK_K == 256 - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI4_K) { - int i = (i0 + i_offset * QI4_K + k / blocks_per_tile_x_row) % mmq_y; - if (need_check) { - i = min(i, i_max); - } - const block_q4_K * bxi = bx0 + i*blocks_per_row + kbxd; - x_dm[i * (WARP_SIZE_GGUF/QI4_K) + i / QI4_K + kbxd] = bxi->dm; - } - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * 8) { - int i = (i0 + i_offset * 8 + k / (WARP_SIZE_GGUF/8)) % mmq_y; - - if (need_check) { - i = min(i, i_max); - } - - const block_q4_K * bxi = bx0 + i*blocks_per_row + (k % (WARP_SIZE_GGUF/8)) / (QI4_K/8); - - const int * scales = (const int *) bxi->scales; - - const int ksc = k % (WARP_SIZE_GGUF/8); - // scale arrangement after the following two lines: sc0,...,sc3, sc4,...,sc7, m0,...,m3, m4,...,m8 - int scales8 = (scales[(ksc%2) + (ksc!=0)] >> (4 * (ksc & (ksc/2)))) & 0x0F0F0F0F; // lower 4 bits - scales8 |= (scales[ksc/2] >> (2 * (ksc % 2))) & 0x30303030; // upper 2 bits - - x_sc[i * (WARP_SIZE_GGUF/8) + i / 8 + ksc] = scales8; - } -} - -static __device__ __forceinline__ float vec_dot_q4_K_q8_1_mul_mat( - const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, - const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { - (void)x_qh; - - const uint8_t * sc = ((const uint8_t *) &x_sc[i * (WARP_SIZE_GGUF/8) + i/8 + k/16]) + 2*((k % 16) / 8); - - const int index_y = j * WARP_SIZE_GGUF + (QR4_K*k) % WARP_SIZE_GGUF; - return vec_dot_q4_K_q8_1_impl_mmq(&x_ql[i * (WARP_SIZE_GGUF + 1) + k], &y_qs[index_y], sc, sc+8, - x_dm[i * (WARP_SIZE_GGUF/QI4_K) + i/QI4_K], &y_ds[index_y/QI8_1]); -} - -static __device__ __forceinline__ float vec_dot_q5_K_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { - - const block_q5_K * bq5_K = (const block_q5_K *) vbq; - - int vl[2]; - int vh[2]; - int u[2*QR5_K]; - float d8[QR5_K]; - - const int bq8_offset = QR5_K * ((iqs/2) / (QI8_1/2)); - const int * ql = (const int *)(bq5_K->qs + 16 * bq8_offset + 4 * ((iqs/2)%4)); - const int * qh = (const int *)(bq5_K->qh + 4 * ((iqs/2)%4)); - - vl[0] = ql[0]; - vl[1] = ql[4]; - - vh[0] = qh[0] >> bq8_offset; - vh[1] = qh[4] >> bq8_offset; - - const uint16_t * scales = (const uint16_t *)bq5_K->scales; - uint16_t aux[2]; - const int j = bq8_offset/2; - if (j < 2) { - aux[0] = scales[j+0] & 0x3f3f; - aux[1] = scales[j+2] & 0x3f3f; - } else { - aux[0] = ((scales[j+2] >> 0) & 0x0f0f) | ((scales[j-2] & 0xc0c0) >> 2); - aux[1] = ((scales[j+2] >> 4) & 0x0f0f) | ((scales[j-0] & 0xc0c0) >> 2); - } - const uint8_t * sc = (const uint8_t *)aux; - const uint8_t * m = sc + 2; - -#pragma unroll - for (int i = 0; i < QR5_K; ++i) { - const block_q8_1 * bq8i = bq8_1 + bq8_offset + i; - d8[i] = __low2float(bq8i->ds); - - const int * q8 = (const int *)bq8i->qs + ((iqs/2)%4); - u[2*i+0] = q8[0]; - u[2*i+1] = q8[4]; - } - - return vec_dot_q5_K_q8_1_impl_vmmq(vl, vh, u, sc, m, bq5_K->dm, d8); -} - -template static __device__ __forceinline__ void allocate_tiles_q5_K(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { - __shared__ int tile_x_ql[mmq_y * (2*WARP_SIZE_GGUF) + mmq_y]; - __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE_GGUF/QI5_K) + mmq_y/QI5_K]; - __shared__ int tile_x_sc[mmq_y * (WARP_SIZE_GGUF/8) + mmq_y/8]; - - *x_ql = tile_x_ql; - *x_dm = tile_x_dm; - *x_sc = tile_x_sc; -} - -template static __device__ __forceinline__ void load_tiles_q5_K( - const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, - int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { - const int kbx = k / QI5_K; // == 0 if QK_K == 256 - const int kqsx = k % QI5_K; // == k if QK_K == 256 - - const block_q5_K * bx0 = (const block_q5_K *) vx; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { - int i = i0 + i_offset; - - if (need_check) { - i = min(i, i_max); - } - - const block_q5_K * bxi = bx0 + i*blocks_per_row + kbx; - const int ky = QR5_K*kqsx; - - const int ql = get_int_from_uint8_aligned(bxi->qs, kqsx); - const int ql0 = (ql >> 0) & 0x0F0F0F0F; - const int ql1 = (ql >> 4) & 0x0F0F0F0F; - - const int qh = get_int_from_uint8_aligned(bxi->qh, kqsx % (QI5_K/4)); - const int qh0 = ((qh >> (2 * (kqsx / (QI5_K/4)) + 0)) << 4) & 0x10101010; - const int qh1 = ((qh >> (2 * (kqsx / (QI5_K/4)) + 1)) << 4) & 0x10101010; - - const int kq0 = ky - ky % (QI5_K/2) + k % (QI5_K/4) + 0; - const int kq1 = ky - ky % (QI5_K/2) + k % (QI5_K/4) + (QI5_K/4); - - x_ql[i * (2*WARP_SIZE_GGUF + 1) + kq0] = ql0 | qh0; - x_ql[i * (2*WARP_SIZE_GGUF + 1) + kq1] = ql1 | qh1; - } - - const int blocks_per_tile_x_row = WARP_SIZE_GGUF / QI5_K; // == 1 if QK_K == 256 - const int kbxd = k % blocks_per_tile_x_row; // == 0 if QK_K == 256 - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI5_K) { - int i = (i0 + i_offset * QI5_K + k / blocks_per_tile_x_row) % mmq_y; - - if (need_check) { - i = min(i, i_max); - } - - const block_q5_K * bxi = bx0 + i*blocks_per_row + kbxd; - x_dm[i * (WARP_SIZE_GGUF/QI5_K) + i / QI5_K + kbxd] = bxi->dm; - } - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * 8) { - int i = (i0 + i_offset * 8 + k / (WARP_SIZE_GGUF/8)) % mmq_y; - - if (need_check) { - i = min(i, i_max); - } - - const block_q5_K * bxi = bx0 + i*blocks_per_row + (k % (WARP_SIZE_GGUF/8)) / (QI5_K/8); - - const int * scales = (const int *) bxi->scales; - - const int ksc = k % (WARP_SIZE_GGUF/8); - - // scale arrangement after the following two lines: sc0,...,sc3, sc4,...,sc7, m0,...,m3, m4,...,m8 - int scales8 = (scales[(ksc%2) + (ksc!=0)] >> (4 * (ksc & (ksc/2)))) & 0x0F0F0F0F; // lower 4 bits - scales8 |= (scales[ksc/2] >> (2 * (ksc % 2))) & 0x30303030; // upper 2 bits - - x_sc[i * (WARP_SIZE_GGUF/8) + i / 8 + ksc] = scales8; - } -} - -static __device__ __forceinline__ float vec_dot_q5_K_q8_1_mul_mat( - const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, - const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { - const uint8_t * sc = ((const uint8_t *) &x_sc[i * (WARP_SIZE_GGUF/8) + i/8 + k/16]) + 2 * ((k % 16) / 8); - - const int index_x = i * (QR5_K*WARP_SIZE_GGUF + 1) + QR5_K*k; - const int index_y = j * WARP_SIZE_GGUF + (QR5_K*k) % WARP_SIZE_GGUF; - return vec_dot_q5_K_q8_1_impl_mmq(&x_ql[index_x], &y_qs[index_y], sc, sc+8, - x_dm[i * (WARP_SIZE_GGUF/QI5_K) + i/QI5_K], &y_ds[index_y/QI8_1]); -} - -static __device__ __forceinline__ float vec_dot_q6_K_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { - - const block_q6_K * bq6_K = (const block_q6_K *) vbq; - - const int bq8_offset = 2 * QR6_K * (iqs / (QI6_K/2)) + (iqs % (QI6_K/2)) / (QI6_K/4); - const int scale_offset = (QI6_K/4) * (iqs / (QI6_K/2)) + (iqs % (QI6_K/2)) / (QI6_K/8); - const int vh_shift = 2 * ((iqs % (QI6_K/2)) / (QI6_K/4)); - - const int vl = get_int_from_uint8(bq6_K->ql, iqs); - const int vh = get_int_from_uint8(bq6_K->qh, (QI6_K/4) * (iqs / (QI6_K/2)) + iqs % (QI6_K/4)) >> vh_shift; - - const int8_t * scales = bq6_K->scales + scale_offset; - - int u[QR6_K]; - float d8[QR6_K]; - -#pragma unroll - for (int i = 0; i < QR6_K; ++i) { - u[i] = get_int_from_int8_aligned(bq8_1[bq8_offset + 2*i].qs, iqs % QI8_1); - d8[i] = __low2float(bq8_1[bq8_offset + 2*i].ds); - } - - return vec_dot_q6_K_q8_1_impl_mmvq(vl, vh, u, scales, __half2float(bq6_K->d), d8); -} - -template static __device__ __forceinline__ void allocate_tiles_q6_K(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { - __shared__ int tile_x_ql[mmq_y * (2*WARP_SIZE_GGUF) + mmq_y]; - __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE_GGUF/QI6_K) + mmq_y/QI6_K]; - __shared__ int tile_x_sc[mmq_y * (WARP_SIZE_GGUF/8) + mmq_y/8]; - - *x_ql = tile_x_ql; - *x_dm = tile_x_dm; - *x_sc = tile_x_sc; -} - -template static __device__ __forceinline__ void load_tiles_q6_K( - const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, - int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { - const int kbx = k / QI6_K; // == 0 if QK_K == 256 - const int kqsx = k % QI6_K; // == k if QK_K == 256 - - const block_q6_K * bx0 = (const block_q6_K *) vx; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { - int i = i0 + i_offset; - - if (need_check) { - i = min(i, i_max); - } - - const block_q6_K * bxi = bx0 + i*blocks_per_row + kbx; - const int ky = QR6_K*kqsx; - - const int ql = get_int_from_uint8(bxi->ql, kqsx); - const int ql0 = (ql >> 0) & 0x0F0F0F0F; - const int ql1 = (ql >> 4) & 0x0F0F0F0F; - - const int qh = get_int_from_uint8(bxi->qh, (QI6_K/4) * (kqsx / (QI6_K/2)) + kqsx % (QI6_K/4)); - const int qh0 = ((qh >> (2 * ((kqsx % (QI6_K/2)) / (QI6_K/4)))) << 4) & 0x30303030; - const int qh1 = (qh >> (2 * ((kqsx % (QI6_K/2)) / (QI6_K/4)))) & 0x30303030; - - const int kq0 = ky - ky % QI6_K + k % (QI6_K/2) + 0; - const int kq1 = ky - ky % QI6_K + k % (QI6_K/2) + (QI6_K/2); - - x_ql[i * (2*WARP_SIZE_GGUF + 1) + kq0] = __vsubss4(ql0 | qh0, 0x20202020); - x_ql[i * (2*WARP_SIZE_GGUF + 1) + kq1] = __vsubss4(ql1 | qh1, 0x20202020); - } - - const int blocks_per_tile_x_row = WARP_SIZE_GGUF / QI6_K; // == 1 if QK_K == 256 - const int kbxd = k % blocks_per_tile_x_row; // == 0 if QK_K == 256 - float * x_dmf = (float *) x_dm; - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI6_K) { - int i = (i0 + i_offset * QI6_K + k / blocks_per_tile_x_row) % mmq_y; - - if (need_check) { - i = min(i, i_max); - } - - const block_q6_K * bxi = bx0 + i*blocks_per_row + kbxd; - - x_dmf[i * (WARP_SIZE_GGUF/QI6_K) + i / QI6_K + kbxd] = __half2float(bxi->d); - } - -#pragma unroll - for (int i0 = 0; i0 < mmq_y; i0 += nwarps * 8) { - int i = (i0 + i_offset * 8 + k / (WARP_SIZE_GGUF/8)) % mmq_y; - - if (need_check) { - i = min(i, i_max); - } - - const block_q6_K * bxi = bx0 + i*blocks_per_row + (k % (WARP_SIZE_GGUF/8)) / 4; - - x_sc[i * (WARP_SIZE_GGUF/8) + i / 8 + k % (WARP_SIZE_GGUF/8)] = get_int_from_int8(bxi->scales, k % (QI6_K/8)); - } -} - -static __device__ __forceinline__ float vec_dot_q6_K_q8_1_mul_mat( - const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, - const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { - const float * x_dmf = (const float *) x_dm; - const float * y_df = (const float *) y_ds; - - const int8_t * sc = ((const int8_t *) &x_sc[i * (WARP_SIZE_GGUF/8) + i/8 + k/8]); - - const int index_x = i * (QR6_K*WARP_SIZE_GGUF + 1) + QR6_K*k; - const int index_y = j * WARP_SIZE_GGUF + (QR6_K*k) % WARP_SIZE_GGUF; - return vec_dot_q6_K_q8_1_impl_mmq(&x_ql[index_x], &y_qs[index_y], sc, x_dmf[i * (WARP_SIZE_GGUF/QI6_K) + i/QI6_K], &y_df[index_y/QI8_1]); -} - -static __device__ __forceinline__ float vec_dot_iq2_xxs_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { - const block_iq2_xxs * bq2 = (const block_iq2_xxs *) vbq; - - const int ib32 = iqs; - const uint16_t * q2 = bq2->qs + 4*ib32; - const uint8_t * aux8 = (const uint8_t *)q2; - const int8_t * q8 = bq8_1[ib32].qs; - uint32_t aux32 = q2[2] | (q2[3] << 16); - int sumi = 0; - for (int l = 0; l < 4; ++l) { - const uint8_t * grid = (const uint8_t *)(iq2xxs_grid + aux8[l]); - const uint8_t signs = ksigns_iq2xs[aux32 & 127]; - for (int j = 0; j < 8; ++j) { - sumi += q8[j] * grid[j] * (signs & kmask_iq2xs[j] ? -1 : 1); - } - q8 += 8; - aux32 >>= 7; - } - const float d = __half2float(bq2->d) * (0.5f + aux32) * __half2float(bq8_1[ib32].ds.x) * 0.25f; - return d * sumi; -} - -static __device__ __forceinline__ float vec_dot_iq2_xs_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { - const block_iq2_xs * bq2 = (const block_iq2_xs *) vbq; - - const int ib32 = iqs; - const uint16_t * q2 = bq2->qs + 4*ib32; - const int8_t * q8 = bq8_1[ib32].qs; - const uint8_t ls1 = bq2->scales[ib32] & 0xf; - const uint8_t ls2 = bq2->scales[ib32] >> 4; - int sumi1 = 0; - for (int l = 0; l < 2; ++l) { - const uint8_t * grid = (const uint8_t *)(iq2xs_grid + (q2[l] & 511)); - const uint8_t signs = ksigns_iq2xs[q2[l] >> 9]; - for (int j = 0; j < 8; ++j) { - sumi1 += q8[j] * grid[j] * (signs & kmask_iq2xs[j] ? -1 : 1); - } - q8 += 8; - } - int sumi2 = 0; - for (int l = 2; l < 4; ++l) { - const uint8_t * grid = (const uint8_t *)(iq2xs_grid + (q2[l] & 511)); - const uint8_t signs = ksigns_iq2xs[q2[l] >> 9]; - for (int j = 0; j < 8; ++j) { - sumi2 += q8[j] * grid[j] * (signs & kmask_iq2xs[j] ? -1 : 1); - } - q8 += 8; - } - const float d = __half2float(bq2->d) * __half2float(bq8_1[ib32].ds.x) * 0.25f; - return d * ((0.5f + ls1) * sumi1 + (0.5f + ls2) * sumi2); -} - -static __device__ __forceinline__ float vec_dot_iq2_s_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - const block_iq2_s * bq2 = (const block_iq2_s *) vbq; - - const int ib32 = iqs; - const int8_t * q8 = bq8_1[ib32].qs; - const uint8_t * signs = bq2->qs + QK_K/8 + 4*ib32; - const uint8_t ls1 = bq2->scales[ib32] & 0xf; - const uint8_t ls2 = bq2->scales[ib32] >> 4; - int sumi1 = 0; - for (int l = 0; l < 2; ++l) { - const uint32_t * grid = (const uint32_t *)(iq2s_grid + (bq2->qs[4*ib32+l] | ((bq2->qh[ib32] << (8-2*l)) & 0x300))); - const uint32_t signs0 = __vcmpeq4(((signs[l] & 0xf) * 0x01010101) & 0x08040201, 0x08040201); - const uint32_t signs1 = __vcmpeq4(((signs[l] >> 4) * 0x01010101) & 0x08040201, 0x08040201); - const int grid_l = __vsub4(grid[0] ^ signs0, signs0); - const int grid_h = __vsub4(grid[1] ^ signs1, signs1); - sumi1 = __dp4a(grid_l, *((const int *)q8 + 0), sumi1); - sumi1 = __dp4a(grid_h, *((const int *)q8 + 1), sumi1); - q8 += 8; - } - int sumi2 = 0; - for (int l = 2; l < 4; ++l) { - const uint32_t * grid = (const uint32_t *)(iq2s_grid + (bq2->qs[4*ib32+l] | ((bq2->qh[ib32] << (8-2*l)) & 0x300))); - const uint32_t signs0 = __vcmpeq4(((signs[l] & 0xf) * 0x01010101) & 0x08040201, 0x08040201); - const uint32_t signs1 = __vcmpeq4(((signs[l] >> 4) * 0x01010101) & 0x08040201, 0x08040201); - const int grid_l = __vsub4(grid[0] ^ signs0, signs0); - const int grid_h = __vsub4(grid[1] ^ signs1, signs1); - sumi2 = __dp4a(grid_l, *((const int *)q8 + 0), sumi2); - sumi2 = __dp4a(grid_h, *((const int *)q8 + 1), sumi2); - q8 += 8; - } - const float d = __half2float(bq2->d) * __low2float(bq8_1[ib32].ds) * 0.25f; - return d * ((0.5f + ls1) * sumi1 + (0.5f + ls2) * sumi2); -#endif -} - -static __device__ __forceinline__ float vec_dot_iq3_xxs_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - const block_iq3_xxs * bq2 = (const block_iq3_xxs *) vbq; - - const int ib32 = iqs; - const uint8_t * q3 = bq2->qs + 8*ib32; - const uint16_t * gas = (const uint16_t *)(bq2->qs + QK_K/4) + 2*ib32; - const int8_t * q8 = bq8_1[ib32].qs; - uint32_t aux32 = gas[0] | (gas[1] << 16); - int sumi = 0; - for (int l = 0; l < 4; ++l) { - const uint32_t * grid1 = iq3xxs_grid + q3[2*l+0]; - const uint32_t * grid2 = iq3xxs_grid + q3[2*l+1]; - const uint32_t * signs = (const uint32_t *)(ksigns64 + (aux32 & 127)); - const int grid_l = __vsub4(grid1[0] ^ signs[0], signs[0]); - const int grid_h = __vsub4(grid2[0] ^ signs[1], signs[1]); - sumi = __dp4a(grid_l, *((int *)q8+0), sumi); - sumi = __dp4a(grid_h, *((int *)q8+1), sumi); - q8 += 8; - aux32 >>= 7; - } - const float d = __half2float(bq2->d) * (0.5f + aux32) * __low2float(bq8_1[ib32].ds) * 0.5f; - return d * sumi; -#endif -} - -static __device__ __forceinline__ float vec_dot_iq3_s_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - const block_iq3_s * bq2 = (const block_iq3_s *) vbq; - - const int ib32 = iqs; - const uint8_t * qs = bq2->qs + 8*ib32; - const int8_t * q8 = bq8_1[ib32].qs; - int sumi = 0; - for (int l = 0; l < 4; ++l) { - const uint32_t * grid1 = iq3xs_grid + (qs[2*l+0] | ((bq2->qh[ib32] << (8 - 2*l)) & 256)); - const uint32_t * grid2 = iq3xs_grid + (qs[2*l+1] | ((bq2->qh[ib32] << (7 - 2*l)) & 256)); - uint32_t signs0 = __vcmpeq4(((bq2->signs[4*ib32+l] & 0xf) * 0x01010101) & 0x08040201, 0x08040201); - uint32_t signs1 = __vcmpeq4(((bq2->signs[4*ib32+l] >> 4) * 0x01010101) & 0x08040201, 0x08040201); - const int grid_l = __vsub4(grid1[0] ^ signs0, signs0); - const int grid_h = __vsub4(grid2[0] ^ signs1, signs1); - sumi = __dp4a(grid_l, *((int *)q8+0), sumi); - sumi = __dp4a(grid_h, *((int *)q8+1), sumi); - q8 += 8; - } - const float d = __half2float(bq2->d) * (0.5f + ((bq2->scales[ib32/2] >> 4*(ib32%2)) & 0xf)) * __low2float(bq8_1[ib32].ds) * 0.5f; - return d * sumi; -#endif -} - -static __device__ __forceinline__ float vec_dot_iq1_s_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - const block_iq1_s * bq1 = (const block_iq1_s *) vbq; - - const int qs_packed = get_int_b2(bq1->qs, iqs); - const uint8_t * qs = (const uint8_t *) &qs_packed; - - const int qh = bq1->qh[iqs]; - - int sumi = 0; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int grid = iq1s_grid_gpu[qs[l0/2] | (((qh >> 3*(l0/2)) & 0x07) << 8)]; - - const int grid0 = (grid >> 0) & 0x0F0F0F0F; - const int grid1 = (grid >> 4) & 0x0F0F0F0F; - - const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0); - const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1); - - sumi = __dp4a(grid0, u0, sumi); - sumi = __dp4a(grid1, u1, sumi); - } - - const float d1q = __half2float(bq1->d) * (((qh >> 11) & 0x0E) + 1); - const float delta = -1.0f + IQ1S_DELTA - (qh & 0x8000) * (2.0f*IQ1S_DELTA/0x8000); - const float2 ds = __half22float2(bq8_1[iqs].ds); - return d1q * (ds.x*sumi + ds.y*delta); -#endif -} - -static __device__ __forceinline__ float vec_dot_iq1_m_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - - const block_iq1_m * bq1 = (const block_iq1_m *) vbq; - - const int qs_packed = get_int_b4(bq1->qs, iqs); - const uint8_t * qs = (const uint8_t *) &qs_packed; - - int sumi[2] = {0}; - float sumf[2] = {0.0f}; -#pragma unroll - for (int l0 = 0; l0 < 8; l0 += 2) { - const int qhl = bq1->qh[2*iqs + l0/4] >> (4 * ((l0/2) % 2)); - - const int grid = iq1s_grid_gpu[qs[l0/2] | ((qhl & 0x07) << 8)]; - - const int grid0 = (grid >> 0) & 0x0F0F0F0F; - const int grid1 = (grid >> 4) & 0x0F0F0F0F; - - const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0); - const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1); - - sumi[l0/4] = __dp4a(grid0, u0, sumi[l0/4]); - sumi[l0/4] = __dp4a(grid1, u1, sumi[l0/4]); - - const float delta = -1.0f + IQ1M_DELTA - (qhl & 0x08) * (2.0f*IQ1M_DELTA/0x08); - int sumy = 0; - sumy = __dp4a(u0, 0x01010101, sumy); - sumy = __dp4a(u1, 0x01010101, sumy); - sumf[l0/4] += delta*sumy; - } - - const uint16_t * sc = (const uint16_t *) bq1->scales; - - iq1m_scale_t scale; - scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00F0) | ((sc[2] >> 4) & 0x0F00) | (sc[3] & 0xF000); - const float d = __half2float(scale.f16) * __low2float(bq8_1[iqs].ds); - - const int tmp = sc[iqs/2] >> (6*(iqs%2)); - const int sc0 = 2*((tmp >> 0) & 0x07) + 1; - const int sc1 = 2*((tmp >> 3) & 0x07) + 1; - return d * ((sumi[0] + sumf[0]) * sc0 + (sumi[1] + sumf[1]) * sc1); -#endif -} - -static __device__ __forceinline__ void get_int_from_table_16(const uint32_t & q4, const uint8_t * values, - int & val1, int & val2) { - - uint32_t aux32; const uint8_t * q8 = (const uint8_t *)&aux32; - aux32 = q4 & 0x0f0f0f0f; - uint16_t v1 = values[q8[0]] | (values[q8[1]] << 8); - uint16_t v2 = values[q8[2]] | (values[q8[3]] << 8); - val1 = v1 | (v2 << 16); - aux32 = (q4 >> 4) & 0x0f0f0f0f; - v1 = values[q8[0]] | (values[q8[1]] << 8); - v2 = values[q8[2]] | (values[q8[3]] << 8); - val2 = v1 | (v2 << 16); -} - -static __device__ __forceinline__ float vec_dot_iq4_nl_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - - const block_iq4_nl * bq = (const block_iq4_nl *) vbq; - - const uint16_t * q4 = (const uint16_t *)bq->qs + 2*iqs; - const int32_t * q8 = (const int32_t *)bq8_1->qs + iqs; - - const uint8_t * values = (const uint8_t *)kvalues_iq4nl; - - int v1, v2; - int sumi1 = 0, sumi2 = 0; - for (int l = 0; l < VDR_Q4_0_Q8_1_MMVQ; ++l) { - const uint32_t aux = q4[2*l] | (q4[2*l+1] << 16); - get_int_from_table_16(aux, values, v1, v2); - sumi1 = __dp4a(v1, q8[l+0], sumi1); - sumi2 = __dp4a(v2, q8[l+4], sumi2); - } - const float d = __half2float(bq->d) * __low2float(bq8_1->ds); - return d * (sumi1 + sumi2); -#endif -} - - -static __device__ __forceinline__ float vec_dot_iq4_xs_q8_1( - const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { -#if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 610 || defined USE_ROCM - const block_iq4_xs * bq4 = (const block_iq4_xs *) vbq; - const uint8_t * values = (const uint8_t *)kvalues_iq4nl; - - // iqs is 0...7 - const int ib32 = iqs; - const int32_t * q8 = (const int *)bq8_1[ib32].qs; - const uint32_t * q4 = (const uint32_t *)bq4->qs + 4*ib32; - const int8_t ls = ((bq4->scales_l[ib32/2] >> 4*(ib32%2)) & 0xf) | (((bq4->scales_h >> 2*ib32) & 3) << 4); - const float d = __half2float(bq4->d) * (ls - 32) * __low2float(bq8_1[ib32].ds); - int v1, v2; - int sumi1 = 0, sumi2 = 0; - for (int j = 0; j < 4; ++j) { - get_int_from_table_16(q4[j], values, v1, v2); - sumi1 = __dp4a(v1, q8[j+0], sumi1); - sumi2 = __dp4a(v2, q8[j+4], sumi2); - } - return d * (sumi1 + sumi2); -#endif -} \ No newline at end of file diff --git a/csrc/quantization/machete/Readme.md b/csrc/libtorch_stable/quantization/machete/Readme.md similarity index 100% rename from csrc/quantization/machete/Readme.md rename to csrc/libtorch_stable/quantization/machete/Readme.md diff --git a/csrc/quantization/machete/generate.py b/csrc/libtorch_stable/quantization/machete/generate.py similarity index 95% rename from csrc/quantization/machete/generate.py rename to csrc/libtorch_stable/quantization/machete/generate.py index e12601e9e974..11a5bbdd13c1 100644 --- a/csrc/quantization/machete/generate.py +++ b/csrc/libtorch_stable/quantization/machete/generate.py @@ -39,10 +39,10 @@ {% for impl_config in impl_configs %} {% set type_sig = gen_type_sig(impl_config.types) -%} {% for s in impl_config.schedules %} -extern torch::Tensor impl_{{type_sig}}_sch_{{gen_sch_sig(s)}}(MMArgs); +extern torch::stable::Tensor impl_{{type_sig}}_sch_{{gen_sch_sig(s)}}(MMArgs); {%- endfor %} -torch::Tensor mm_dispatch_{{type_sig}}(MMArgs args) { +torch::stable::Tensor mm_dispatch_{{type_sig}}(MMArgs args) { [[maybe_unused]] auto M = args.A.size(0); [[maybe_unused]] auto N = args.B.size(1); [[maybe_unused]] auto K = args.A.size(1); @@ -59,14 +59,14 @@ if (*args.maybe_schedule == "{{ gen_sch_sig(s) }}") return impl_{{type_sig}}_sch_{{ gen_sch_sig(s) }}(args); {%- endfor %} - TORCH_CHECK_NOT_IMPLEMENTED(false, "machete_gemm(..) is not implemented for " + STD_TORCH_CHECK_NOT_IMPLEMENTED(false, "machete_gemm(..) is not implemented for " "schedule = ", *args.maybe_schedule); } {%- endfor %} -static inline std::optional maybe_scalartype( - std::optional const& t) { +static inline std::optional maybe_scalartype( + std::optional const& t) { if (!t) { return std::nullopt; } else { @@ -74,7 +74,7 @@ }; } -torch::Tensor mm_dispatch(MMArgs args) { +torch::stable::Tensor mm_dispatch(MMArgs args) { auto out_type = args.maybe_out_type.value_or(args.A.scalar_type()); auto a_type = args.A.scalar_type(); auto maybe_g_scales_type = maybe_scalartype(args.maybe_group_scales); @@ -105,19 +105,19 @@ } {%- endfor %} - TORCH_CHECK_NOT_IMPLEMENTED( + STD_TORCH_CHECK_NOT_IMPLEMENTED( false, "machete_mm(..) is not implemented for " - "a_type=", args.A.scalar_type(), + "a_type=", torch::headeronly::toString(args.A.scalar_type()), ", b_type=", args.b_type.str(), - ", out_type=", out_type, + ", out_type=", torch::headeronly::toString(out_type), ", with_group_scale_type=", maybe_g_scales_type - ? toString(*maybe_g_scales_type) : "None", + ? torch::headeronly::toString(*maybe_g_scales_type) : "None", ", with_group_zeropoint_type=", maybe_g_zeros_type - ? toString(*maybe_g_zeros_type) : "None", + ? torch::headeronly::toString(*maybe_g_zeros_type) : "None", ", with_channel_scale_type=", maybe_ch_scales_type - ? toString(*maybe_ch_scales_type) : "None", + ? torch::headeronly::toString(*maybe_ch_scales_type) : "None", ", with_token_scale_type=", maybe_tok_scales_type - ? toString(*maybe_tok_scales_type) : "None", + ? torch::headeronly::toString(*maybe_tok_scales_type) : "None", "; implemented types are: \\n", {%- for impl_config in impl_configs %} {% set t = impl_config.types -%} @@ -197,7 +197,7 @@ {% for sch in schs %} {% set sch_sig = gen_sch_sig(sch) -%} -torch::Tensor +torch::stable::Tensor impl_{{type_sig}}_sch_{{sch_sig}}(MMArgs args) { return run_impl>(args); } @@ -212,7 +212,7 @@ namespace machete { -torch::Tensor prepack_B_dispatch(PrepackBArgs args) { +torch::stable::Tensor prepack_B_dispatch(PrepackBArgs args) { auto convert_type = args.maybe_group_scales_type.value_or(args.a_type); {%- for t in types %} {% set b_type = unsigned_type_with_bitwidth(t.b_num_bits) %} @@ -231,12 +231,12 @@ } {%- endfor %} - TORCH_CHECK_NOT_IMPLEMENTED(false, + STD_TORCH_CHECK_NOT_IMPLEMENTED(false, "prepack_B_dispatch(..) is not implemented for " - "atype = ", args.a_type, + "atype = ", torch::headeronly::toString(args.a_type), ", b_type = ", args.b_type.str(), ", with_group_scales_type= ", args.maybe_group_scales_type ? - toString(*args.maybe_group_scales_type) : "None"); + torch::headeronly::toString(*args.maybe_group_scales_type) : "None"); } }; // namespace machete diff --git a/csrc/quantization/machete/machete_collective_builder.cuh b/csrc/libtorch_stable/quantization/machete/machete_collective_builder.cuh similarity index 100% rename from csrc/quantization/machete/machete_collective_builder.cuh rename to csrc/libtorch_stable/quantization/machete/machete_collective_builder.cuh diff --git a/csrc/quantization/machete/machete_interleaving_utils.cuh b/csrc/libtorch_stable/quantization/machete/machete_interleaving_utils.cuh similarity index 100% rename from csrc/quantization/machete/machete_interleaving_utils.cuh rename to csrc/libtorch_stable/quantization/machete/machete_interleaving_utils.cuh diff --git a/csrc/quantization/machete/machete_mainloop.cuh b/csrc/libtorch_stable/quantization/machete/machete_mainloop.cuh similarity index 100% rename from csrc/quantization/machete/machete_mainloop.cuh rename to csrc/libtorch_stable/quantization/machete/machete_mainloop.cuh diff --git a/csrc/quantization/machete/machete_mm_kernel.cuh b/csrc/libtorch_stable/quantization/machete/machete_mm_kernel.cuh similarity index 87% rename from csrc/quantization/machete/machete_mm_kernel.cuh rename to csrc/libtorch_stable/quantization/machete/machete_mm_kernel.cuh index cc50e68b058e..db3321a39db8 100644 --- a/csrc/quantization/machete/machete_mm_kernel.cuh +++ b/csrc/libtorch_stable/quantization/machete/machete_mm_kernel.cuh @@ -1,8 +1,6 @@ #pragma once -#include -#include -#include +#include // clang-format off // The cutlass include order matters (annoyingly) @@ -175,19 +173,23 @@ struct MacheteKernelTemplate { static Arguments create_arguments( cudaStream_t stream, - torch::Tensor const& A, // MxK matrix - torch::Tensor const& B, // KxN prepacked matrix - torch::Tensor& D, // MxN matrix - std::optional const& maybe_g_scales, // scale_KxN matrix - std::optional const& maybe_g_zeros, // scale_KxN matrix + torch::stable::Tensor const& A, // MxK matrix + torch::stable::Tensor const& B, // KxN prepacked matrix + torch::stable::Tensor& D, // MxN matrix + std::optional const& + maybe_g_scales, // scale_KxN matrix + std::optional const& + maybe_g_zeros, // scale_KxN matrix std::optional maybe_group_size, - std::optional const& maybe_ch_scales, // len N vector - std::optional const& maybe_tok_scales) // len M vector + std::optional const& + maybe_ch_scales, // len N vector + std::optional const& + maybe_tok_scales) // len M vector { static_assert(!with_group_zeropoints || with_group_scales); int M = A.size(0), N = B.size(1), K = A.size(1); - TORCH_CHECK(D.size(0) == M && D.size(1) == N); + STD_TORCH_CHECK(D.size(0) == M && D.size(1) == N); auto layout_A = make_cute_layout(A, "A"); auto layout_D = make_cute_layout(D, "D"); @@ -216,29 +218,29 @@ struct MacheteKernelTemplate { maybe_group_size == -1 ? K : maybe_group_size.value_or(K); int const scale_k = (K + group_size - 1) / group_size; - TORCH_CHECK(size<0>(layout_A) == M && size<1>(layout_A) == K); - TORCH_CHECK(size<0>(layout_D) == M && size<1>(layout_D) == N); + STD_TORCH_CHECK(size<0>(layout_A) == M && size<1>(layout_A) == K); + STD_TORCH_CHECK(size<0>(layout_D) == M && size<1>(layout_D) == N); if constexpr (with_group_scales) { - TORCH_CHECK(S_group_ptr && layout_S_group); - TORCH_CHECK((size<0>(*layout_S_group) == scale_k && - size<1>(*layout_S_group) == N)); + STD_TORCH_CHECK(S_group_ptr && layout_S_group); + STD_TORCH_CHECK((size<0>(*layout_S_group) == scale_k && + size<1>(*layout_S_group) == N)); } else { - TORCH_CHECK(!S_group_ptr, "Scales not supported"); + STD_TORCH_CHECK(!S_group_ptr, "Scales not supported"); } if constexpr (with_group_zeropoints) { - TORCH_CHECK(Z_group_ptr && layout_Z_group); - TORCH_CHECK((size<0>(*layout_Z_group) == scale_k && - size<1>(*layout_Z_group) == N)); - TORCH_CHECK(layout_S_group && *layout_Z_group == *layout_S_group, - "Scales and zeros must have the same layout"); + STD_TORCH_CHECK(Z_group_ptr && layout_Z_group); + STD_TORCH_CHECK((size<0>(*layout_Z_group) == scale_k && + size<1>(*layout_Z_group) == N)); + STD_TORCH_CHECK(layout_S_group && *layout_Z_group == *layout_S_group, + "Scales and zeros must have the same layout"); } else { - TORCH_CHECK(!Z_group_ptr, "Zeropoints not supported"); + STD_TORCH_CHECK(!Z_group_ptr, "Zeropoints not supported"); } if constexpr (with_channel_scales || with_token_scales) { - TORCH_CHECK( + STD_TORCH_CHECK( (maybe_ch_scales->numel() == N || maybe_ch_scales->numel() == 1) && (maybe_tok_scales->numel() == M || maybe_tok_scales->numel() == 1)); } @@ -298,11 +300,12 @@ struct MacheteKernelTemplate { Gemm gemm_op; cutlass::Status status = gemm_op.initialize(args, workspace, stream); - TORCH_CHECK(status == cutlass::Status::kSuccess, - "Machete kernel failed to initialize workspace"); + STD_TORCH_CHECK(status == cutlass::Status::kSuccess, + "Machete kernel failed to initialize workspace"); status = gemm_op.run(stream); - TORCH_CHECK(status == cutlass::Status::kSuccess, "Machete kernel failed"); + STD_TORCH_CHECK(status == cutlass::Status::kSuccess, + "Machete kernel failed"); } }; diff --git a/csrc/libtorch_stable/quantization/machete/machete_mm_launcher.cuh b/csrc/libtorch_stable/quantization/machete/machete_mm_launcher.cuh new file mode 100644 index 000000000000..fcf7f18aac2e --- /dev/null +++ b/csrc/libtorch_stable/quantization/machete/machete_mm_launcher.cuh @@ -0,0 +1,80 @@ +#pragma once + +#include "machete_mm_kernel.cuh" +#include "cutlass_extensions/torch_utils.hpp" +#include "core/scalar_type.hpp" +#include "libtorch_stable/torch_utils.h" + +#include +#include + +#include +#include +#include + +namespace machete { + +struct MMArgs { + torch::stable::Tensor const& A; + torch::stable::Tensor const& B; + vllm::ScalarType const& b_type; + std::optional const& maybe_out_type; + std::optional const& maybe_group_scales; + std::optional const& maybe_group_zeros; + std::optional maybe_group_size; + std::optional const& maybe_channel_scales; + std::optional const& maybe_token_scales; + std::optional maybe_schedule; +}; + +struct SupportedSchedulesArgs { + torch::headeronly::ScalarType a_type; + vllm::ScalarType b_type; + std::optional maybe_group_scales_type; + std::optional maybe_group_zeros_type; + std::optional maybe_channel_scales_type; + std::optional maybe_token_scales_type; + std::optional maybe_out_type; +}; + +torch::stable::Tensor mm_dispatch(MMArgs args); + +std::vector supported_schedules_dispatch( + SupportedSchedulesArgs args); + +template +torch::stable::Tensor run_impl(MMArgs args) { + const torch::stable::accelerator::DeviceGuard device_guard( + args.A.get_device_index()); + + auto device = args.A.device(); + auto stream = get_current_cuda_stream(device.index()); + + int M = args.A.size(0); + int N = args.B.size(1); + int K = args.A.size(1); + + // Allocate output + torch::stable::Tensor D = torch::stable::empty( + {M, N}, equivalent_scalar_type_v, + std::nullopt, device); + + auto arguments = MacheteKernel::create_arguments( + stream, // + args.A, args.B, D, args.maybe_group_scales, args.maybe_group_zeros, + args.maybe_group_size, args.maybe_channel_scales, + args.maybe_token_scales); + STD_TORCH_CHECK(MacheteKernel::can_implement(arguments), + "Machete kernel cannot be run with these arguments"); + + size_t workspace_size = MacheteKernel::get_workspace_size(arguments); + torch::stable::Tensor workspace = + torch::stable::empty(workspace_size, torch::headeronly::ScalarType::Byte, + std::nullopt, device); + + MacheteKernel::run(arguments, workspace.mutable_data_ptr(), stream); + + return D; +}; + +}; // namespace machete \ No newline at end of file diff --git a/csrc/quantization/machete/machete_prepack_kernel.cuh b/csrc/libtorch_stable/quantization/machete/machete_prepack_kernel.cuh similarity index 94% rename from csrc/quantization/machete/machete_prepack_kernel.cuh rename to csrc/libtorch_stable/quantization/machete/machete_prepack_kernel.cuh index d002355ca49d..e1e054e5a007 100644 --- a/csrc/quantization/machete/machete_prepack_kernel.cuh +++ b/csrc/libtorch_stable/quantization/machete/machete_prepack_kernel.cuh @@ -3,6 +3,7 @@ #include "machete_mm_kernel.cuh" #include "cutlass_extensions/cute_utils.cuh" #include "cutlass_extensions/torch_utils.hpp" +#include namespace machete { @@ -60,8 +61,8 @@ static void prepack_B_template( auto ilvd_NKbNbKL_to_offset = PrepackedLayoutB::ilvd_NKbNbKL_to_offset(shape(B_layout)); - TORCH_CHECK(size<0>(B_layout) % size<0>(TileShapeNKL{}) == 0); - TORCH_CHECK(size<1>(B_layout) % size<1>(TileShapeNKL{}) == 0); + STD_TORCH_CHECK(size<0>(B_layout) % size<0>(TileShapeNKL{}) == 0); + STD_TORCH_CHECK(size<1>(B_layout) % size<1>(TileShapeNKL{}) == 0); auto N_tiles = size<0>(B_layout) / size<0>(TileShapeNKL{}); auto K_tiles = size<1>(B_layout) / size<1>(TileShapeNKL{}); diff --git a/csrc/quantization/machete/machete_prepack_launcher.cuh b/csrc/libtorch_stable/quantization/machete/machete_prepack_launcher.cuh similarity index 65% rename from csrc/quantization/machete/machete_prepack_launcher.cuh rename to csrc/libtorch_stable/quantization/machete/machete_prepack_launcher.cuh index 634b651a4d10..94f6f684bc05 100644 --- a/csrc/quantization/machete/machete_prepack_launcher.cuh +++ b/csrc/libtorch_stable/quantization/machete/machete_prepack_launcher.cuh @@ -3,39 +3,47 @@ #include "machete_prepack_kernel.cuh" #include "cutlass_extensions/torch_utils.hpp" #include "core/scalar_type.hpp" +#include "libtorch_stable/torch_utils.h" + +#include +#include + +#include namespace machete { struct PrepackBArgs { - torch::Tensor const& B; - at::ScalarType a_type; + torch::stable::Tensor const& B; + torch::headeronly::ScalarType a_type; vllm::ScalarType b_type; - std::optional maybe_group_scales_type; + std::optional maybe_group_scales_type; }; template -torch::Tensor prepack_impl(torch::Tensor const B) { - const at::cuda::OptionalCUDAGuard device_guard(device_of(B)); +torch::stable::Tensor prepack_impl(torch::stable::Tensor const& B) { + const torch::stable::accelerator::DeviceGuard device_guard( + B.get_device_index()); using ElementB = typename PrepackedLayoutB::ElementB; using PPBlockShape_NK = typename PrepackedLayoutB::PPBlockShape_NK; auto device = B.device(); - auto stream = at::cuda::getCurrentCUDAStream(device.index()); + auto stream = get_current_cuda_stream(device.index()); auto B_ptr = static_cast(B.const_data_ptr()); // elements per storage item for B auto eles_per_storage = - (B.dtype().itemsize() * 8) / cute::sizeof_bits_v; + (B.element_size() * 8) / cute::sizeof_bits_v; // torch B passed in is/should be (packed_K,N), the kernel expects (N,K,L) (to // match cutlass using (N,K,L) for B), so we transpose B to (N,packed_K,L) - auto Bt_packed = B.t(); + auto Bt_packed = torch::stable::transpose(B, 0, 1); - TORCH_CHECK( + STD_TORCH_CHECK( (B.size(0) * eles_per_storage) % size<1>(PPBlockShape_NK{}) == 0, "B.shape[0] (in terms of unpacked elements) must be a multiple of ", size<1>(PPBlockShape_NK{})); - TORCH_CHECK(B.size(1) % size<0>(PPBlockShape_NK{}) == 0, - "B.shape[1] must be a multiple of ", size<0>(PPBlockShape_NK{})); + STD_TORCH_CHECK(B.size(1) % size<0>(PPBlockShape_NK{}) == 0, + "B.shape[1] must be a multiple of ", + size<0>(PPBlockShape_NK{})); using StrideB = cutlass::detail::TagToStrideB_t; auto const l_Bt_packed = make_cute_layout(Bt_packed, "B"); @@ -49,7 +57,7 @@ torch::Tensor prepack_impl(torch::Tensor const B) { // new_shape = (N, packed_K, L) * (1, eles_per_storage, 1) -> (N, K, L) // new_stride = (s0, s1, s2) * (eles_per_storage, 1, eles_per_storage) // when s1 == 1 - TORCH_CHECK(stride<1>(l_Bt_packed) == 1); + STD_TORCH_CHECK(stride<1>(l_Bt_packed) == 1); // clang-format off auto const layout_Bt = make_layout( transform_with_idx(l_Bt_packed.shape(), [&](auto ele, auto idx) { @@ -61,7 +69,9 @@ torch::Tensor prepack_impl(torch::Tensor const B) { // clang-format on // Allocate output - torch::Tensor D = torch::empty_like(B, {}, at::MemoryFormat::Contiguous); + torch::stable::Tensor D = torch::stable::empty( + B.sizes(), B.scalar_type(), std::nullopt, B.device(), std::nullopt, + torch::headeronly::MemoryFormat::Contiguous); prepack_B_template( stream, B_ptr, layout_Bt, static_cast(D.mutable_data_ptr())); @@ -69,6 +79,6 @@ torch::Tensor prepack_impl(torch::Tensor const B) { return D; }; -torch::Tensor prepack_B_dispatch(PrepackBArgs args); +torch::stable::Tensor prepack_B_dispatch(PrepackBArgs args); }; // namespace machete \ No newline at end of file diff --git a/csrc/quantization/machete/machete_prepacked_layout.cuh b/csrc/libtorch_stable/quantization/machete/machete_prepacked_layout.cuh similarity index 99% rename from csrc/quantization/machete/machete_prepacked_layout.cuh rename to csrc/libtorch_stable/quantization/machete/machete_prepacked_layout.cuh index 4a7d6341e6c0..c16a2ab8a33d 100644 --- a/csrc/quantization/machete/machete_prepacked_layout.cuh +++ b/csrc/libtorch_stable/quantization/machete/machete_prepacked_layout.cuh @@ -1,9 +1,5 @@ #pragma once -#include -#include -#include - // clang-format off // The cutlass include order matters (annoyingly) diff --git a/csrc/libtorch_stable/quantization/machete/machete_pytorch.cu b/csrc/libtorch_stable/quantization/machete/machete_pytorch.cu new file mode 100644 index 000000000000..7736d5b3ece4 --- /dev/null +++ b/csrc/libtorch_stable/quantization/machete/machete_pytorch.cu @@ -0,0 +1,77 @@ +#include "machete_mm_launcher.cuh" +#include "machete_prepack_launcher.cuh" +#include "core/scalar_type.hpp" + +#include +#include +#include + +namespace machete { + +using namespace vllm; + +std::vector supported_schedules( + torch::headeronly::ScalarType a_type, int64_t b_type_id, + std::optional maybe_group_scales_type, + std::optional maybe_group_zeros_type, + std::optional maybe_channel_scales_type, + std::optional maybe_token_scales_type, + std::optional maybe_out_type) { + ScalarType const b_type = ScalarType::from_id(b_type_id); + return supported_schedules_dispatch({ + .a_type = a_type, + .b_type = b_type, + .maybe_group_scales_type = maybe_group_scales_type, + .maybe_group_zeros_type = maybe_group_zeros_type, + .maybe_channel_scales_type = maybe_channel_scales_type, + .maybe_token_scales_type = maybe_token_scales_type, + .maybe_out_type = maybe_out_type, + }); +} + +torch::stable::Tensor mm( + torch::stable::Tensor const& A, torch::stable::Tensor const& B, + int64_t b_type_id, + std::optional const& maybe_out_type, + std::optional const& maybe_group_scales, + std::optional const& maybe_group_zeros, + std::optional maybe_group_size, + std::optional const& maybe_channel_scales, + std::optional const& maybe_token_scales, + std::optional maybe_schedule) { + ScalarType const b_type = ScalarType::from_id(b_type_id); + return mm_dispatch({.A = A, + .B = B, + .b_type = b_type, + .maybe_out_type = maybe_out_type, + .maybe_group_scales = maybe_group_scales, + .maybe_group_zeros = maybe_group_zeros, + .maybe_group_size = maybe_group_size, + .maybe_channel_scales = maybe_channel_scales, + .maybe_token_scales = maybe_token_scales, + .maybe_schedule = maybe_schedule}); +} + +torch::stable::Tensor prepack_B( + torch::stable::Tensor const& B, torch::headeronly::ScalarType const& a_type, + int64_t b_type_id, + std::optional const& + maybe_group_scales_type) { + ScalarType const b_type = ScalarType::from_id(b_type_id); + return prepack_B_dispatch( + {.B = B, + .a_type = a_type, + .b_type = b_type, + .maybe_group_scales_type = maybe_group_scales_type}); +} + +STABLE_TORCH_LIBRARY_IMPL(_C, CUDA, m) { + m.impl("machete_prepack_B", TORCH_BOX(&prepack_B)); + m.impl("machete_mm", TORCH_BOX(&mm)); +} + +STABLE_TORCH_LIBRARY_IMPL(_C, CompositeExplicitAutograd, m) { + m.impl("machete_supported_schedules", TORCH_BOX(&supported_schedules)); +} + +}; // namespace machete diff --git a/csrc/libtorch_stable/quantization/w8a8/cutlass/c3x/scaled_mm_blockwise_sm90_fp8_dispatch.cuh b/csrc/libtorch_stable/quantization/w8a8/cutlass/c3x/scaled_mm_blockwise_sm90_fp8_dispatch.cuh index cf62e81fd75b..529b28ceece5 100644 --- a/csrc/libtorch_stable/quantization/w8a8/cutlass/c3x/scaled_mm_blockwise_sm90_fp8_dispatch.cuh +++ b/csrc/libtorch_stable/quantization/w8a8/cutlass/c3x/scaled_mm_blockwise_sm90_fp8_dispatch.cuh @@ -25,33 +25,43 @@ using namespace cute; template + class EpilogueScheduler, class MainloopScheduler, + bool swap_ab_ = false> struct cutlass_3x_gemm_fp8_blockwise { + static constexpr bool swap_ab = swap_ab_; using ElementAB = cutlass::float_e4m3_t; using ElementA = ElementAB; using LayoutA = cutlass::layout::RowMajor; + using LayoutA_Transpose = typename cutlass::layout::LayoutTranspose::type; static constexpr int AlignmentA = 128 / cutlass::sizeof_bits::value; using ElementB = ElementAB; using LayoutB = cutlass::layout::ColumnMajor; + using LayoutB_Transpose = typename cutlass::layout::LayoutTranspose::type; static constexpr int AlignmentB = 128 / cutlass::sizeof_bits::value; using ElementD = OutType; using LayoutD = cutlass::layout::RowMajor; + using LayoutD_Transpose = typename cutlass::layout::LayoutTranspose::type; static constexpr int AlignmentD = 128 / cutlass::sizeof_bits::value; using ElementC = void; // TODO: support bias using LayoutC = LayoutD; + using LayoutC_Transpose = LayoutD_Transpose; static constexpr int AlignmentC = AlignmentD; using ElementAccumulator = float; using ElementCompute = float; using ElementBlockScale = float; - using ScaleConfig = cutlass::detail::Sm90BlockwiseScaleConfig< + using ScaleConfig = conditional_t; + cute::GMMA::Major::K, cute::GMMA::Major::MN>, + cutlass::detail::Sm90BlockwiseScaleConfig< + ScaleGranularityM, ScaleGranularityN, ScaleGranularityK, + cute::GMMA::Major::MN, cute::GMMA::Major::K>>; using LayoutSFA = decltype(ScaleConfig::deduce_layoutSFA()); using LayoutSFB = decltype(ScaleConfig::deduce_layoutSFB()); @@ -71,30 +81,46 @@ struct cutlass_3x_gemm_fp8_blockwise { ElementAccumulator, ElementCompute, ElementC, - LayoutC, + conditional_t, AlignmentC, ElementD, - LayoutD, + conditional_t, AlignmentD, EpilogueScheduler, DefaultOperation >::CollectiveOp; - using CollectiveMainloop = typename cutlass::gemm::collective::CollectiveBuilder< - ArchTag, - OperatorClass, - ElementA, - cute::tuple, - AlignmentA, - ElementB, - cute::tuple, - AlignmentB, - ElementAccumulator, - MmaTileShape, - ClusterShape, - cutlass::gemm::collective::StageCountAutoCarveout(sizeof(typename CollectiveEpilogue::SharedStorage))>, - MainloopScheduler - >::CollectiveOp; + using CollectiveMainloop = conditional_t, + AlignmentB, + ElementA, + cute::tuple, + AlignmentA, + ElementAccumulator, + MmaTileShape, + ClusterShape, + cutlass::gemm::collective::StageCountAutoCarveout(sizeof(typename CollectiveEpilogue::SharedStorage))>, + MainloopScheduler + >::CollectiveOp, + typename cutlass::gemm::collective::CollectiveBuilder< + ArchTag, + OperatorClass, + ElementA, + cute::tuple, + AlignmentA, + ElementB, + cute::tuple, + AlignmentB, + ElementAccumulator, + MmaTileShape, + ClusterShape, + cutlass::gemm::collective::StageCountAutoCarveout(sizeof(typename CollectiveEpilogue::SharedStorage))>, + MainloopScheduler + >::CollectiveOp>; using KernelType = enable_sm90_or_later, CollectiveMainloop, CollectiveEpilogue>>; @@ -107,6 +133,7 @@ void cutlass_gemm_caller_blockwise(torch::stable::Tensor& out, torch::stable::Te torch::stable::Tensor const& b, torch::stable::Tensor const& a_scales, torch::stable::Tensor const& b_scales) { + static constexpr bool swap_ab = Gemm::swap_ab; using GemmKernel = typename Gemm::GemmKernel; using StrideA = typename Gemm::GemmKernel::StrideA; using StrideB = typename Gemm::GemmKernel::StrideB; @@ -122,8 +149,6 @@ void cutlass_gemm_caller_blockwise(torch::stable::Tensor& out, torch::stable::Te int32_t m = a.size(0), n = b.size(1), k = a.size(1); - STD_TORCH_CHECK(m % 4 == 0, "m must be divisible by 4"); - StrideA a_stride; StrideB b_stride; StrideC c_stride; @@ -132,12 +157,16 @@ void cutlass_gemm_caller_blockwise(torch::stable::Tensor& out, torch::stable::Te b_stride = cutlass::make_cute_packed_stride(StrideB{}, cute::make_shape(n, k, 1)); c_stride = - cutlass::make_cute_packed_stride(StrideC{}, cute::make_shape(m, n, 1)); + cutlass::make_cute_packed_stride( + StrideC{}, swap_ab ? cute::make_shape(n, m, 1) + : cute::make_shape(m, n, 1)); - LayoutSFA layout_SFA = - ScaleConfig::tile_atom_to_shape_SFA(make_shape(m, n, k, 1)); - LayoutSFB layout_SFB = - ScaleConfig::tile_atom_to_shape_SFB(make_shape(m, n, k, 1)); + LayoutSFA layout_SFA = swap_ab + ? ScaleConfig::tile_atom_to_shape_SFA(make_shape(n, m, k, 1)) + : ScaleConfig::tile_atom_to_shape_SFA(make_shape(m, n, k, 1)); + LayoutSFB layout_SFB = swap_ab + ? ScaleConfig::tile_atom_to_shape_SFB(make_shape(n, m, k, 1)) + : ScaleConfig::tile_atom_to_shape_SFB(make_shape(m, n, k, 1)); auto a_ptr = static_cast(a.data_ptr()); auto b_ptr = static_cast(b.data_ptr()); @@ -145,15 +174,25 @@ void cutlass_gemm_caller_blockwise(torch::stable::Tensor& out, torch::stable::Te auto b_scales_ptr = static_cast(b_scales.data_ptr()); typename GemmKernel::MainloopArguments mainloop_args{}; - mainloop_args.ptr_A = a_ptr; - mainloop_args.dA = a_stride; - mainloop_args.ptr_B = b_ptr; - mainloop_args.dB = b_stride; - mainloop_args.ptr_SFA = a_scales_ptr; mainloop_args.layout_SFA = layout_SFA; - mainloop_args.ptr_SFB = b_scales_ptr; mainloop_args.layout_SFB = layout_SFB; - auto prob_shape = cute::make_shape(m, n, k, 1); + if (swap_ab) { + mainloop_args.ptr_A = b_ptr; + mainloop_args.dA = b_stride; + mainloop_args.ptr_B = a_ptr; + mainloop_args.dB = a_stride; + mainloop_args.ptr_SFA = b_scales_ptr; + mainloop_args.ptr_SFB = a_scales_ptr; + } else { + mainloop_args.ptr_A = a_ptr; + mainloop_args.dA = a_stride; + mainloop_args.ptr_B = b_ptr; + mainloop_args.dB = b_stride; + mainloop_args.ptr_SFA = a_scales_ptr; + mainloop_args.ptr_SFB = b_scales_ptr; + } + auto prob_shape = swap_ab ? cute::make_shape(n, m, k, 1) + : cute::make_shape(m, n, k, 1); auto c_ptr = static_cast(out.data_ptr()); typename GemmKernel::EpilogueArguments epilogue_args{ @@ -168,12 +207,21 @@ void cutlass_gemm_blockwise_sm90_fp8_dispatch(torch::stable::Tensor& out, torch::stable::Tensor const& b, torch::stable::Tensor const& a_scales, torch::stable::Tensor const& b_scales) { - // TODO: better heuristics + bool swap_ab = (a.size(0) % 4) != 0; + if (!swap_ab) { + cutlass_gemm_caller_blockwise, + Shape<_1, _2, _1>, cutlass::epilogue::TmaWarpSpecializedCooperative, + cutlass::gemm::KernelTmaWarpSpecializedCooperativeFP8BlockScaledAccum>>( + out, a, b, a_scales, b_scales); + return; + } + cutlass_gemm_caller_blockwise, - Shape<_1, _2, _1>, cutlass::epilogue::TmaWarpSpecializedCooperative, - cutlass::gemm::KernelTmaWarpSpecializedCooperativeFP8BlockScaledAccum>>( - out, a, b, a_scales, b_scales); + OutType, 128, 1, 128, Shape<_128, _16, _128>, + Shape<_1, _1, _1>, cutlass::epilogue::TmaWarpSpecialized, + cutlass::gemm::KernelTmaWarpSpecializedPingpongFP8BlockScaledAccum, + true>>(out, a, b, a_scales, b_scales); } } // namespace vllm \ No newline at end of file diff --git a/csrc/libtorch_stable/quantization/w8a8/cutlass/scaled_mm_entry.cu b/csrc/libtorch_stable/quantization/w8a8/cutlass/scaled_mm_entry.cu index 0f9873cbf88e..8bdb4f56795b 100644 --- a/csrc/libtorch_stable/quantization/w8a8/cutlass/scaled_mm_entry.cu +++ b/csrc/libtorch_stable/quantization/w8a8/cutlass/scaled_mm_entry.cu @@ -1,3 +1,4 @@ +#include #include #include @@ -174,15 +175,20 @@ bool cutlass_scaled_mm_supports_block_fp8(int64_t cuda_device_capability) { bool cutlass_group_gemm_supported(int64_t cuda_device_capability) { // CUTLASS grouped FP8 kernels need at least CUDA 12.3 and SM90 (Hopper) - // or CUDA 12.8 and SM100 (Blackwell) + // or CUDA 12.8 and SM100 (Blackwell). Only report archs that have an + // actual cutlass_moe_mm dispatch compiled into this file. #if defined CUDA_VERSION - if (cuda_device_capability >= 100) { + #if defined ENABLE_CUTLASS_MOE_SM100 && ENABLE_CUTLASS_MOE_SM100 + if (cuda_device_capability >= 100 && cuda_device_capability < 110) { return CUDA_VERSION >= 12080; } - if (cuda_device_capability >= 90) { + #endif + #if defined ENABLE_CUTLASS_MOE_SM90 && ENABLE_CUTLASS_MOE_SM90 + if (cuda_device_capability >= 90 && cuda_device_capability < 100) { return CUDA_VERSION >= 12030; } + #endif #endif return false; diff --git a/csrc/libtorch_stable/torch_bindings.cpp b/csrc/libtorch_stable/torch_bindings.cpp index 204feed4a258..0aabcc757dc7 100644 --- a/csrc/libtorch_stable/torch_bindings.cpp +++ b/csrc/libtorch_stable/torch_bindings.cpp @@ -34,6 +34,39 @@ STABLE_TORCH_LIBRARY_FRAGMENT(_C, ops) { // TODO: Remove this once ROCm upgrade to torch 2.11. ops.def("get_cuda_view_from_cpu_tensor(Tensor cpu_tensor) -> Tensor"); + // Machete (Dense) Optimized Mixed Precision GEMM for Hopper. + ops.def( + "machete_supported_schedules(" + " ScalarType a_type," + " int b_type," + " ScalarType? maybe_group_scales_type," + " ScalarType? maybe_group_zeros_type," + " ScalarType? maybe_channel_scales_type," + " ScalarType? maybe_token_scales_type," + " ScalarType? maybe_out_type" + ") -> str[]"); + ops.def( + "machete_mm(" + " Tensor A," + " Tensor B," + " int b_type," + " ScalarType? out_type," + " Tensor? group_scales," + " Tensor? group_zeros," + " int? group_size," + " Tensor? channel_scales," + " Tensor? token_scales," + " str? schedule" + ") -> Tensor"); + ops.def( + "machete_prepack_B(" + " Tensor B," + " ScalarType a_type," + " int b_type," + " ScalarType? group_scales_type" + ") -> Tensor"); + // conditionally compiled so impl registration is in source file + // Marlin GEMM ops.def( "marlin_gemm(Tensor a, Tensor? c_or_none, Tensor b_q_weight, " @@ -336,12 +369,13 @@ STABLE_TORCH_LIBRARY_FRAGMENT(_C, ops) { // Apply Root Mean Square (RMS) Normalization to the input tensor. ops.def( - "rms_norm(Tensor! result, Tensor input, Tensor weight, float epsilon) -> " + "rms_norm(Tensor! result, Tensor input, Tensor? weight, float epsilon) " + "-> " "()"); // In-place fused Add and RMS Normalization. ops.def( - "fused_add_rms_norm(Tensor! input, Tensor! residual, Tensor weight, " + "fused_add_rms_norm(Tensor! input, Tensor! residual, Tensor? weight, " "float epsilon) -> ()"); // Layernorm-quant @@ -428,6 +462,19 @@ STABLE_TORCH_LIBRARY_FRAGMENT(_C, ops) { "float eps) -> (Tensor, Tensor)"); #endif + // Horizontally-fused MiniMax-M3 QK-norm + partial NeoX RoPE + KV-insert. + ops.def( + "fused_minimax_m3_qknorm_rope_kv_insert(" + "Tensor! qkv, Tensor q_norm_weight, Tensor k_norm_weight, " + "Tensor cos_sin_cache, Tensor positions, int num_heads, " + "int num_kv_heads, int rotary_dim, float eps, " + "Tensor? index_q_norm_weight, Tensor? index_k_norm_weight, " + "int num_index_heads, " + "Tensor? slot_mapping, Tensor? index_slot_mapping, " + "Tensor!? kv_cache, Tensor!? index_cache, " + "int block_size, Tensor!? q_out, Tensor!? index_q_out, " + "str kv_cache_dtype) -> ()"); + // Apply repetition penalties to logits in-place. ops.def( "apply_repetition_penalties_(Tensor! logits, Tensor prompt_mask, " @@ -455,9 +502,11 @@ STABLE_TORCH_LIBRARY_FRAGMENT(_C, ops) { ops.def("mul_and_silu(Tensor! out, Tensor input) -> ()"); // SwiGLU activation with input clamping. + // alpha scales the sigmoid (gate * sigmoid(alpha * gate)); beta is added to + // the up half (up + beta). Defaults alpha=1.0, beta=0.0 give silu(gate)*up. ops.def( - "silu_and_mul_with_clamp(Tensor! result, Tensor input, float limit) " - "-> ()"); + "silu_and_mul_with_clamp(Tensor! result, Tensor input, float limit, " + "float alpha=1.0, float beta=0.0) -> ()"); // Activation function used in GeGLU with `none` approximation. ops.def("gelu_and_mul(Tensor! out, Tensor input) -> ()"); @@ -524,34 +573,6 @@ STABLE_TORCH_LIBRARY_FRAGMENT(_C, ops) { // Post processing for GPTQ. ops.def("gptq_shuffle(Tensor! q_weight, Tensor q_perm, int bit) -> ()"); - // Dequantization for GGML. - ops.def( - "ggml_dequantize(Tensor W, int type, SymInt m, SymInt n, ScalarType? " - "dtype) -> Tensor"); - - // mmvq kernel for GGML. - ops.def( - "ggml_mul_mat_vec_a8(Tensor W, Tensor X, int type, SymInt row) " - "-> Tensor"); - - // mmq kernel for GGML. - ops.def( - "ggml_mul_mat_a8(Tensor W, Tensor X, int type, SymInt row) -> Tensor"); - - // moe kernel for GGML. - ops.def( - "ggml_moe_a8(Tensor X, Tensor W, " - "Tensor sorted_token_ids, Tensor expert_ids, Tensor " - "num_tokens_post_padded, " - "int type, SymInt row, SymInt top_k, SymInt tokens) -> Tensor"); - - ops.def( - "ggml_moe_a8_vec(Tensor X, Tensor W, " - "Tensor topk_ids, int top_k, " - "int type, SymInt row, SymInt tokens) -> Tensor"); - - ops.def("ggml_moe_get_block_size(int type) -> int"); - // Mamba selective scan kernel ops.def( "selective_scan_fwd(Tensor! u, Tensor! delta," @@ -674,6 +695,8 @@ STABLE_TORCH_LIBRARY_IMPL(_C, CUDA, ops) { ops.impl("minimax_allreduce_rms", TORCH_BOX(&minimax_allreduce_rms)); ops.impl("minimax_allreduce_rms_qk", TORCH_BOX(&minimax_allreduce_rms_qk)); #endif + ops.impl("fused_minimax_m3_qknorm_rope_kv_insert", + TORCH_BOX(&fused_minimax_m3_qknorm_rope_kv_insert)); // Sampler kernels (shared CUDA/ROCm) ops.impl("apply_repetition_penalties_", @@ -708,12 +731,7 @@ STABLE_TORCH_LIBRARY_IMPL(_C, CUDA, ops) { ops.impl("gptq_gemm", TORCH_BOX(&gptq_gemm)); ops.impl("gptq_shuffle", TORCH_BOX(&gptq_shuffle)); - // GGML kernels - ops.impl("ggml_dequantize", TORCH_BOX(&ggml_dequantize)); - ops.impl("ggml_mul_mat_vec_a8", TORCH_BOX(&ggml_mul_mat_vec_a8)); - ops.impl("ggml_mul_mat_a8", TORCH_BOX(&ggml_mul_mat_a8)); - ops.impl("ggml_moe_a8", TORCH_BOX(&ggml_moe_a8)); - ops.impl("ggml_moe_a8_vec", TORCH_BOX(&ggml_moe_a8_vec)); + // Mamba kernels ops.impl("selective_scan_fwd", TORCH_BOX(&selective_scan_fwd)); ops.impl("paged_attention_v1", TORCH_BOX(&paged_attention_v1)); @@ -757,9 +775,6 @@ STABLE_TORCH_LIBRARY_IMPL(_C, CompositeExplicitAutograd, ops) { ops.impl("cutlass_scaled_mm_supports_fp4", TORCH_BOX(&cutlass_scaled_mm_supports_fp4)); #endif - - // GGML block size lookup (no tensor args) - ops.impl("ggml_moe_get_block_size", TORCH_BOX(&ggml_moe_get_block_size)); } // Cache ops diff --git a/csrc/ops.h b/csrc/ops.h index e39bae08f198..ec3f5e187cc3 100644 --- a/csrc/ops.h +++ b/csrc/ops.h @@ -34,11 +34,11 @@ torch::Tensor weak_ref_tensor(torch::Tensor& tensor) { // rms_norm and fused_add_rms_norm declarations also exist in // csrc/libtorch_stable/ops.h (torch::stable ABI for CUDA). They remain here // because the CPU build still uses these torch::Tensor declarations. -void rms_norm(torch::Tensor& out, torch::Tensor& input, torch::Tensor& weight, - double epsilon); +void rms_norm(torch::Tensor& out, torch::Tensor& input, + std::optional weight, double epsilon); void fused_add_rms_norm(torch::Tensor& input, torch::Tensor& residual, - torch::Tensor& weight, double epsilon); + std::optional weight, double epsilon); // rotary_embedding also exist in csrc/libtorch_stable/ops.h (torch::stable // ABI for CUDA). It remains here because the CPU build still uses these @@ -50,7 +50,8 @@ void rotary_embedding(torch::Tensor& positions, torch::Tensor& query, void silu_and_mul(torch::Tensor& out, torch::Tensor& input); -void silu_and_mul_clamp(torch::Tensor& out, torch::Tensor& input, double limit); +void silu_and_mul_clamp(torch::Tensor& out, torch::Tensor& input, double limit, + double alpha = 1.0, double beta = 0.0); void silu_and_mul_quant(torch::Tensor& out, torch::Tensor& input, torch::Tensor& scale); diff --git a/csrc/quantization/machete/machete_mm_launcher.cuh b/csrc/quantization/machete/machete_mm_launcher.cuh deleted file mode 100644 index cabe0af46f06..000000000000 --- a/csrc/quantization/machete/machete_mm_launcher.cuh +++ /dev/null @@ -1,75 +0,0 @@ -#pragma once - -#include -#include - -#include "machete_mm_kernel.cuh" -#include "cutlass_extensions/torch_utils.hpp" -#include "core/scalar_type.hpp" - -namespace machete { - -struct MMArgs { - torch::Tensor const& A; - torch::Tensor const& B; - vllm::ScalarType const& b_type; - std::optional const& maybe_out_type; - std::optional const& maybe_group_scales; - std::optional const& maybe_group_zeros; - std::optional maybe_group_size; - std::optional const& maybe_channel_scales; - std::optional const& maybe_token_scales; - std::optional maybe_schedule; -}; - -struct SupportedSchedulesArgs { - at::ScalarType a_type; - vllm::ScalarType b_type; - std::optional maybe_group_scales_type; - std::optional maybe_group_zeros_type; - std::optional maybe_channel_scales_type; - std::optional maybe_token_scales_type; - std::optional maybe_out_type; -}; - -torch::Tensor mm_dispatch(MMArgs args); - -std::vector supported_schedules_dispatch( - SupportedSchedulesArgs args); - -template -torch::Tensor run_impl(MMArgs args) { - const at::cuda::OptionalCUDAGuard device_guard(device_of(args.A)); - - auto device = args.A.device(); - auto stream = at::cuda::getCurrentCUDAStream(device.index()); - - int M = args.A.size(0); - int N = args.B.size(1); - int K = args.A.size(1); - - // Allocate output - torch::Tensor D = torch::empty( - {M, N}, - torch::TensorOptions() - .dtype(equivalent_scalar_type_v) - .device(device)); - - auto arguments = MacheteKernel::create_arguments( - stream, // - args.A, args.B, D, args.maybe_group_scales, args.maybe_group_zeros, - args.maybe_group_size, args.maybe_channel_scales, - args.maybe_token_scales); - TORCH_CHECK(MacheteKernel::can_implement(arguments), - "Machete kernel cannot be run with these arguments"); - - size_t workspace_size = MacheteKernel::get_workspace_size(arguments); - torch::Tensor workspace = torch::empty( - workspace_size, torch::TensorOptions().dtype(torch::kU8).device(device)); - - MacheteKernel::run(arguments, workspace.mutable_data_ptr(), stream); - - return D; -}; - -}; // namespace machete \ No newline at end of file diff --git a/csrc/quantization/machete/machete_pytorch.cu b/csrc/quantization/machete/machete_pytorch.cu deleted file mode 100644 index 05a51ee21ddb..000000000000 --- a/csrc/quantization/machete/machete_pytorch.cu +++ /dev/null @@ -1,73 +0,0 @@ -#include "machete_mm_launcher.cuh" -#include "machete_prepack_launcher.cuh" -#include "core/scalar_type.hpp" - -#include "core/registration.h" - -namespace machete { - -using namespace vllm; - -std::vector supported_schedules( - at::ScalarType a_type, int64_t b_type_id, - std::optional maybe_group_scales_type, - std::optional maybe_group_zeros_type, - std::optional maybe_channel_scales_type, - std::optional maybe_token_scales_type, - std::optional maybe_out_type) { - ScalarType const b_type = ScalarType::from_id(b_type_id); - return supported_schedules_dispatch({ - .a_type = a_type, - .b_type = b_type, - .maybe_group_scales_type = maybe_group_scales_type, - .maybe_group_zeros_type = maybe_group_zeros_type, - .maybe_channel_scales_type = maybe_channel_scales_type, - .maybe_token_scales_type = maybe_token_scales_type, - .maybe_out_type = maybe_out_type, - }); -} - -torch::Tensor mm(torch::Tensor const& A, torch::Tensor const& B, - int64_t b_type_id, - std::optional const& maybe_out_type, - std::optional const& maybe_group_scales, - std::optional const& maybe_group_zeros, - std::optional maybe_group_size, - std::optional const& maybe_channel_scales, - std::optional const& maybe_token_scales, - std::optional maybe_schedule) { - ScalarType const b_type = ScalarType::from_id(b_type_id); - return mm_dispatch({.A = A, - .B = B, - .b_type = b_type, - .maybe_out_type = maybe_out_type, - .maybe_group_scales = maybe_group_scales, - .maybe_group_zeros = maybe_group_zeros, - .maybe_group_size = maybe_group_size, - .maybe_channel_scales = maybe_channel_scales, - .maybe_token_scales = maybe_token_scales, - .maybe_schedule = maybe_schedule}); -} - -torch::Tensor prepack_B( - torch::Tensor const& B, at::ScalarType const& a_type, int64_t b_type_id, - std::optional const& maybe_group_scales_type) { - ScalarType const b_type = ScalarType::from_id(b_type_id); - return prepack_B_dispatch( - {.B = B, - .a_type = a_type, - .b_type = b_type, - .maybe_group_scales_type = maybe_group_scales_type}); -} - -TORCH_LIBRARY_IMPL_EXPAND(TORCH_EXTENSION_NAME, CUDA, m) { - m.impl("machete_prepack_B", &prepack_B); - m.impl("machete_mm", &mm); -} - -// use CatchAll since supported_schedules has no tensor arguments -TORCH_LIBRARY_IMPL(TORCH_EXTENSION_NAME, CatchAll, m) { - m.impl("machete_supported_schedules", &supported_schedules); -} - -}; // namespace machete diff --git a/csrc/torch_bindings.cpp b/csrc/torch_bindings.cpp index 941e4a61c1a5..cfd185394a41 100644 --- a/csrc/torch_bindings.cpp +++ b/csrc/torch_bindings.cpp @@ -68,39 +68,6 @@ TORCH_LIBRARY_EXPAND(TORCH_EXTENSION_NAME, ops) { // custom types: // https://docs.google.com/document/d/18fBMPuOJ0fY5ZQ6YyrHUppw9FA332CpNtgB6SOIgyuA - // Machete (Dense) Optimized Mixed Precision GEMM for Hopper. - ops.def( - "machete_supported_schedules(" - " ScalarType a_type," - " int b_type," - " ScalarType? maybe_group_scales_type," - " ScalarType? maybe_group_zeros_type," - " ScalarType? maybe_channel_scales_type," - " ScalarType? maybe_token_scales_type," - " ScalarType? maybe_out_type" - ") -> str[]"); - ops.def( - "machete_mm(" - " Tensor A," - " Tensor B," - " int b_type," - " ScalarType? out_type," - " Tensor? group_scales," - " Tensor? group_zeros," - " int? group_size," - " Tensor? channel_scales," - " Tensor? token_scales," - " str? schedule" - ") -> Tensor"); - ops.def( - "machete_prepack_B(" - " Tensor B," - " ScalarType a_type," - " int b_type," - " ScalarType? group_scales_type" - ") -> Tensor"); - // conditionally compiled so impl registration is in source file - #endif } diff --git a/docker/Dockerfile b/docker/Dockerfile index d03da7bcc370..d7823f321154 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -261,7 +261,10 @@ RUN --mount=type=cache,target=/opt/uv/cache \ # Explicitly set the list to avoid issues with torch 2.2 # See https://github.com/pytorch/pytorch/pull/123243 # From versions.json: .torch.cuda_arch_list -ARG torch_cuda_arch_list='7.5 8.0 8.6 8.9 9.0 10.0 11.0 12.0+PTX' +# Do not add +PTX here: vLLM filters torch's top-level PTX flag when it +# converts global gencode flags into per-kernel arch lists. If a specific +# kernel needs PTX, add +PTX to that kernel's CMake arch list instead. +ARG torch_cuda_arch_list='7.5 8.0 8.6 8.9 9.0 10.0 11.0 12.0' ENV TORCH_CUDA_ARCH_LIST=${torch_cuda_arch_list} #################### BUILD BASE IMAGE #################### @@ -548,9 +551,17 @@ RUN --mount=type=cache,target=/opt/uv/cache \ fi && \ python3 setup.py bdist_wheel --dist-dir=dist --py-limited-api=cp38 +# Record the wheel checksum so downstream stages can bust their layer cache +# when the wheel changes, without copying the wheel itself into the image. +RUN sha256sum dist/*.whl > dist/wheel.sha256 + # Copy extension wheels from extensions-build stage for later use COPY --from=extensions-build /tmp/ep_kernels_workspace/dist /tmp/ep_kernels_workspace/dist +# Record the EP kernels wheel checksum for the same cache-busting purpose. +RUN sha256sum /tmp/ep_kernels_workspace/dist/*.whl \ + > /tmp/ep_kernels_workspace/dist/wheels.sha256 + # Check the size of the wheel if RUN_WHEEL_CHECK is true COPY .buildkite/check-wheel-size.py check-wheel-size.py # sync the default value with .buildkite/check-wheel-size.py @@ -838,6 +849,11 @@ ARG PYTORCH_NIGHTLY # Install vLLM wheel first, so that torch etc will be installed. # Check whether to install torch nightly instead of release for this build. COPY --from=base /workspace/torch_lib_versions.txt torch_lib_versions.txt +# Copy only the wheel checksum (a few bytes) so a wheel change invalidates this +# install layer. The wheel itself is bind-mounted below and never enters the +# image. Without this the bind mount is not part of the layer cache key, so a +# warm BuildKit agent can skip the install and ship a stale wheel. +COPY --from=build /workspace/dist/wheel.sha256 /tmp/vllm-wheel.sha256 RUN --mount=type=bind,from=build,src=/workspace/dist,target=/vllm-workspace/dist \ --mount=type=cache,target=/opt/uv/cache \ if [ "${PYTORCH_NIGHTLY}" = "1" ]; then \ @@ -860,7 +876,10 @@ uv pip list # Pytorch now installs NVSHMEM, setting LD_LIBRARY_PATH ENV LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH -# Install EP kernels wheels (DeepEP) that have been built in the `build` stage +# Install EP kernels wheels (DeepEP) that have been built in the `build` stage. +# As with the vLLM wheel above, copy only the checksum to bust the layer cache +# and bind-mount the wheel for the actual install to keep it out of the image. +COPY --from=build /tmp/ep_kernels_workspace/dist/wheels.sha256 /tmp/ep-kernels-wheels.sha256 RUN --mount=type=bind,from=build,src=/tmp/ep_kernels_workspace/dist,target=/vllm-workspace/ep_kernels/dist \ --mount=type=cache,target=/opt/uv/cache \ uv pip install --system ep_kernels/dist/*.whl --verbose \ @@ -994,7 +1013,8 @@ ARG PIP_EXTRA_INDEX_URL UV_EXTRA_INDEX_URL ENV UV_HTTP_TIMEOUT=500 # install kv_connectors if requested -ARG torch_cuda_arch_list='7.5 8.0 8.6 8.9 9.0 10.0 11.0 12.0+PTX' +# Do not add +PTX here; see the main TORCH_CUDA_ARCH_LIST comment above. +ARG torch_cuda_arch_list='7.5 8.0 8.6 8.9 9.0 10.0 11.0 12.0' ENV TORCH_CUDA_ARCH_LIST=${torch_cuda_arch_list} RUN --mount=type=cache,target=/opt/uv/cache \ --mount=type=bind,source=requirements/kv_connectors.txt,target=/tmp/kv_connectors.txt,ro \ diff --git a/docker/Dockerfile.cpu b/docker/Dockerfile.cpu index 4df401395fab..61bad68b4425 100644 --- a/docker/Dockerfile.cpu +++ b/docker/Dockerfile.cpu @@ -168,6 +168,12 @@ RUN --mount=type=cache,target=/root/.cache/uv \ ######################### TRITON-CPU BUILD IMAGE ######################### FROM base AS vllm-triton-cpu-build +# Support for cross-compilation with x86 ISA including AVX2 and AVX512: docker build --build-arg VLLM_CPU_X86="true" ... +# Re-declared here because this stage is `FROM base` (not `vllm-build`), so it +# does not inherit the ARG/ENV defined there. Without it, the guard below would +# see an empty value and build triton-cpu on non-x86 targets (e.g. arm64). +ARG VLLM_CPU_X86=0 + WORKDIR /vllm-workspace RUN mkdir dist @@ -269,6 +275,11 @@ ENV HF_HUB_DOWNLOAD_TIMEOUT 60 ######################### RELEASE IMAGE ######################### FROM base AS vllm-openai +# Re-declared here because this stage is `FROM base` (not `vllm-build`), so the +# RUN below that gates the triton-cpu wheel install on $VLLM_CPU_X86 would +# otherwise see an empty value and try to install it on non-x86 targets. +ARG VLLM_CPU_X86=0 + WORKDIR /vllm-workspace RUN --mount=type=cache,target=/root/.cache/uv \ diff --git a/docker/Dockerfile.rocm_base b/docker/Dockerfile.rocm_base index 208ce863f6b3..a3b2a539bd95 100644 --- a/docker/Dockerfile.rocm_base +++ b/docker/Dockerfile.rocm_base @@ -1,7 +1,7 @@ ARG BASE_IMAGE=rocm/dev-ubuntu-22.04:7.2.3-complete -ARG TRITON_BRANCH="ba5c1517" +ARG TRITON_BRANCH="0f380657" ARG TRITON_REPO="https://github.com/ROCm/triton.git" -ARG PYTORCH_BRANCH="8514f051" # release/2.10 as of 3/17 +ARG PYTORCH_BRANCH="d0c8b1f3" # release/2.11 as of 6/09 ARG PYTORCH_REPO="https://github.com/ROCm/pytorch.git" ARG PYTORCH_VISION_BRANCH="v0.24.1" ARG PYTORCH_VISION_REPO="https://github.com/pytorch/vision.git" @@ -114,12 +114,10 @@ ARG TRITON_REPO RUN git clone ${TRITON_REPO} # Cherry picking the following # https://github.com/triton-lang/triton/pull/8991 -# https://github.com/triton-lang/triton/pull/9541 RUN cd triton \ && git checkout ${TRITON_BRANCH} \ && git config --global user.email "you@example.com" && git config --global user.name "Your Name" \ && git cherry-pick 555d04f \ - && git cherry-pick dd998b6 \ && if [ ! -f setup.py ]; then cd python; fi \ && python3 setup.py bdist_wheel --dist-dir=dist \ && mkdir -p /app/install && cp dist/*.whl /app/install diff --git a/docker/versions.json b/docker/versions.json index 15f77648a9c0..3145cfcc53ef 100644 --- a/docker/versions.json +++ b/docker/versions.json @@ -35,7 +35,7 @@ "default": "false" }, "TORCH_CUDA_ARCH_LIST": { - "default": "7.5 8.0 8.6 8.9 9.0 10.0 11.0 12.0+PTX" + "default": "7.5 8.0 8.6 8.9 9.0 10.0 11.0 12.0" }, "MAX_JOBS": { "default": "2" diff --git a/docs/assets/contributing/dockerfile-stages-dependency.png b/docs/assets/contributing/dockerfile-stages-dependency.png index 90aaf01a0b7e..8cb98a8f4e45 100644 Binary files a/docs/assets/contributing/dockerfile-stages-dependency.png and b/docs/assets/contributing/dockerfile-stages-dependency.png differ diff --git a/docs/contributing/ci/failures.md b/docs/contributing/ci/failures.md index a0038f461a04..c57c430478f5 100644 --- a/docs/contributing/ci/failures.md +++ b/docs/contributing/ci/failures.md @@ -60,15 +60,21 @@ the failure? ## Logs Wrangling -Download a job's log (no Buildkite login required): - +Logs are public; no Buildkite login needed. [.buildkite/scripts/ci-fetch-log.sh](../../../.buildkite/scripts/ci-fetch-log.sh) +saves each log as `ci--.log`, stripped of timestamps and +ANSI codes: ```bash -# Find the failing job. Each row's URL is .../builds/#: -gh pr checks --repo vllm-project/vllm +# All failed jobs in a PR's latest build (current branch's PR if omitted): +.buildkite/scripts/ci-fetch-log.sh --pr + +# All failed jobs in a build (--soft also includes soft-failed jobs; +# --all fetches every finished job): +.buildkite/scripts/ci-fetch-log.sh "https://buildkite.com/vllm/ci/builds/" -# Download + strip timestamps/ANSI in one step: +# One job — `gh pr checks` URLs (#) and web UI URLs (?sid=) both +# work; pass "-" as a second argument to stream to stdout: .buildkite/scripts/ci-fetch-log.sh "https://buildkite.com/vllm/ci/builds/#" ``` diff --git a/docs/design/attention_backends.md b/docs/design/attention_backends.md index a585cd77ffb6..8a261c502ede 100644 --- a/docs/design/attention_backends.md +++ b/docs/design/attention_backends.md @@ -170,8 +170,8 @@ Priority is **1 = highest** (tried first). | Backend | Version | Dtypes | KV Dtypes | Block Sizes | Head Sizes | Sink | Non-Causal | MM Prefix | DCP | Attention Types | Compute Cap. | | ------- | ------- | ------ | --------- | ----------- | ---------- | ---- | ---------- | --------- | --- | --------------- | ------------ | | `CPU_ATTN` | | fp16, bf16, fp32 | `auto`, `fp8`, `fp8_e4m3`, `fp8_e5m2` | %16 | 32, 64, 80, 96, 112, 128, 160, 192, 224, 256, 512 | ❌ | ❌ | ❌ | ❌ | All | N/A | -| `FLASHINFER` | Native† | fp16, bf16 | `auto`, `float16`, `bfloat16`, `fp8`, `fp8_e4m3`, `fp8_e5m2` | 16, 32, 64 | 64, 128, 256, 512 | ❌ | ❌ | ❌ | ✅ | Decoder | 7.x-9.x | -| `FLASHINFER` | TRTLLM† | fp16, bf16 | `auto`, `float16`, `bfloat16`, `fp8`, `fp8_e4m3`, `fp8_e5m2`, `nvfp4` | 16, 32, 64 | 64, 128, 256, 512 | ✅ | ❌ | ❌ | ✅ | Decoder | 10.x | +| `FLASHINFER` | Native† | fp16, bf16 | `auto`, `float16`, `bfloat16`, `fp8`, `fp8_e4m3`, `fp8_e5m2` | 16, 32, 64, 128, 256, 512, 1024 | 64, 128, 256, 512 | ❌ | ❌ | ❌ | ✅ | Decoder | 7.x-9.x | +| `FLASHINFER` | TRTLLM† | fp16, bf16 | `auto`, `float16`, `bfloat16`, `fp8`, `fp8_e4m3`, `fp8_e5m2`, `nvfp4` | 16, 32, 64, 128, 256, 512, 1024 | 64, 128, 256, 512 | ✅ | ❌ | ❌ | ✅ | Decoder | 10.x | | `FLASH_ATTN` | FA2* | fp16, bf16 | `auto`, `float16`, `bfloat16` | %16 | Any | ❌ | ✅ | ❌ | ✅ | All | ≥8.0 | | `FLASH_ATTN` | FA3* | fp16, bf16 | `auto`, `float16`, `bfloat16`, `fp8`, `fp8_e4m3`, `fp8_e5m2` | %16 | Any | ✅ | ✅ | ❌ | ✅ | All | 9.x | | `FLASH_ATTN` | FA4* | fp16, bf16 | `auto`, `float16`, `bfloat16` | %16 | Any | ✅ | ✅ | ❌ | ✅ | All | ≥10.0 | @@ -188,6 +188,18 @@ Priority is **1 = highest** (tried first). > > **\*** Specify the FlashAttention version via `--attention-config.flash_attn_version=2`, `3`, or `4`. Default is FA4 on SM100+ (Blackwell), FA3 on SM90 (Hopper), FA2 otherwise. +## MiniMax M3 Sparse Attention Backends + +Block-sparse GQA backend used by MiniMax M3 sparse ("lightning indexer") +layers. It is wired in directly by the model and is not part of the +automatic priority lists above. A lightning indexer scores KV blocks, the +top-k blocks (plus fixed init/local blocks) are selected, and attention +attends only to those blocks; index keys live in a separate side cache. + +| Backend | Dtypes | KV Dtypes | Block Sizes | Head Sizes | Sink | Non-Causal | MM Prefix | DCP | Attention Types | Compute Cap. | +| ------- | ------ | --------- | ----------- | ---------- | ---- | ---------- | --------- | --- | --------------- | ------------ | +| `MINIMAX_M3_SPARSE` | bf16, fp16 | `bfloat16`, `fp8`, `fp8_e4m3`, `fp8_e5m2` | 128 | 128 | ❌ | ❌ | ❌ | ❌ | Decoder | Any | + ## MLA (Multi-head Latent Attention) Backends MLA uses separate backends for prefill and decode phases. @@ -202,9 +214,9 @@ hardware and configuration. | Backend | Description | Dtypes | Compute Cap. | Notes | | ------- | ----------- | ------ | ------------ | ----- | | `FLASH_ATTN`‡ | FlashAttention varlen (FA2/FA3/FA4) | fp16, bf16 | Any | FA4 on SM100+, FA3 on SM90, FA2 otherwise | -| `TRTLLM_RAGGED` | TensorRT-LLM ragged attention | fp16, bf16 | 10.x | DeepSeek R1 dims only | -| `FLASHINFER` | FlashInfer CUTLASS backend | fp16, bf16 | 10.x | DeepSeek R1 dims only | -| `TOKENSPEED_MLA` | | fp16, bf16 | 10.x | DeepSeek R1 dims only | +| `TRTLLM_RAGGED` | TensorRT-LLM ragged attention | fp16, bf16 | 10.x | (qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128) or (qk_nope_head_dim=192, qk_rope_head_dim=64, v_head_dim=256) only | +| `FLASHINFER` | FlashInfer CUTLASS backend | fp16, bf16 | 10.x | (qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128) only | +| `TOKENSPEED_MLA` | | fp16, bf16 | 10.x | (qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128) only | > **‡** Automatic selection tries FlashAttention first. On Blackwell > (SM100), the fallback order is TRT-LLM Ragged, FlashInfer, then @@ -240,6 +252,6 @@ default on NVIDIA is `FLASHMLA_SPARSE_DSV4`. | Backend | Dtypes | KV Dtypes | Block Sizes | Head Sizes | Sink | Non-Causal | Sparse | MM Prefix | DCP | Attention Types | Compute Cap. | | ------- | ------ | --------- | ----------- | ---------- | ---- | ---------- | ------ | --------- | --- | --------------- | ------------ | -| `FLASHINFER_MLA_SPARSE_DSV4` | fp16, bf16 | `auto` | Any | Any | ❌ | ❌ | ❌ | ❌ | ❌ | Decoder | Any | -| `FLASHMLA_SPARSE_DSV4` | bf16 | `auto`, `bfloat16`, `fp8_ds_mla`, `fp8` | 256 | 512 | ❌ | ❌ | ✅ | ❌ | ❌ | Decoder | 9.x-10.x | +| `FLASHINFER_MLA_SPARSE_DSV4` | bf16 | `auto`, `bfloat16`, `fp8` | Any | Any | ❌ | ❌ | ❌ | ❌ | ❌ | Decoder | Any | +| `FLASHMLA_SPARSE_DSV4` | bf16 | `auto`, `fp8_ds_mla`, `fp8` | 256 | 512 | ❌ | ❌ | ✅ | ❌ | ❌ | Decoder | 9.x-10.x | | `ROCM_FLASHMLA_SPARSE_DSV4` | fp16, bf16 | `auto` | Any | Any | ❌ | ❌ | ❌ | ❌ | ❌ | Decoder | N/A | diff --git a/docs/design/cuda_graphs_multimodal.md b/docs/design/cuda_graphs_multimodal.md index dd0e47a1950f..1db82ffa6887 100644 --- a/docs/design/cuda_graphs_multimodal.md +++ b/docs/design/cuda_graphs_multimodal.md @@ -2,6 +2,8 @@ The [CUDA Graphs](cuda_graphs.md) infrastructure in vLLM primarily targets the **decoder** (language model) forward pass. vLLM also supports capturing the **encoder** (vision transformer) forward pass as CUDA Graphs, independently from the decoder. This is based on . +For two-tower vision encoders (e.g., DeepSeek-OCR's SAM + CLIP with dynamic tiling), a **dual-path graph** mode captures two independent sets of CUDA graphs — one for the global image path and one for the local patch path — enabling independent budget selection and partial eager fallback per path. This is based on . + !!! note Encoder CUDA Graphs are orthogonal to decoder CUDA Graphs — both can be enabled simultaneously. Encoder graphs capture the vision encoder execution (e.g., ViT in Qwen3-VL), while decoder graphs capture the language model execution as described in the [CUDA Graphs design document](cuda_graphs.md). @@ -11,6 +13,8 @@ Vision encoder inference incurs CUDA kernel launch overhead on the host side. Th Encoder CUDA Graphs eliminate this overhead by pre-capturing the full encoder forward pass at multiple token budget levels during model initialization, then replaying the appropriate graph at runtime. +For two-tower vision encoders such as DeepSeek-OCR (SAM + CLIP with dynamic tiling), the global image path and local patch path have independent token profiles (272 tokens per global image vs. 100 tokens per local patch). Capturing a single monolithic graph for both paths would significantly reduce packing efficiency. The dual-path graph mode captures each path as a separate set of budgets, allowing the manager to pack and replay each path independently. + ## Design The encoder CUDA Graph system uses a **budget-based capture/replay** strategy, managed by [EncoderCudaGraphManager][vllm.v1.worker.encoder_cudagraph.EncoderCudaGraphManager]. The system contains the following core components: @@ -37,10 +41,14 @@ class BudgetGraphMetadata: Budgets are auto-generated as power-of-2 levels from a model-provided range via `get_encoder_cudagraph_budget_range()`, with the maximum budget always included even if it does not fall on a power-of-2 boundary. Budgets can also be explicitly specified by the user via `encoder_cudagraph_token_budgets` in `CompilationConfig`. +When `EncoderCudaGraphConfig.enable_dual_path_graph` is `True`, the manager generates two independent budget lists — `global_token_budgets` (multiples of `global_token_per_image`) and `local_token_budgets` (multiples of `local_token_per_patch`) — and stores captured graphs under `budget_graphs["global"]` and `budget_graphs["local"]` respectively. + ### Greedy bin-packing at runtime When a batch of images arrives, the manager sorts images by output token count (smallest first) and greedily packs as many images as possible into each sub-batch while staying within the **largest** token budget and the maximum batch size. Once a sub-batch is finalized (the next image would overflow either constraint), the manager finds the **smallest** budget that fits the sub-batch's total tokens and replays the corresponding CUDA Graph. This repeats until the batch is exhausted. Images that exceed all budgets fall back to eager execution. +For dual-path models, the manager routes to `_execute_local_dual_path()`, which constrains both global and local token budgets simultaneously during packing (see [Dual-Path graph capture](#dual-path-graph-capture)). + For each graph replay: 1. Call `prepare_encoder_cudagraph_replay_buffers()` to compute buffer values (including `pixel_values` and precomputed metadata) from actual batch inputs. @@ -48,6 +56,42 @@ For each graph replay: 3. Replay the CUDA Graph. 4. Clone outputs from `output_buffer` (cloning is necessary since the buffer is reused across replays). +### Dual-Path graph capture + +For two-tower vision encoders (e.g., DeepSeek-OCR), the `EncoderCudaGraphConfig` sets `enable_dual_path_graph=True` and provides `global_token_per_image` / `local_token_per_patch`. The manager captures two independent sets of CUDA graphs — one for the **global** image path and one for the **local** patch path — stored under `budget_graphs["global"]` and `budget_graphs["local"]` respectively. + +**Budget generation.** Two separate budget lists are generated: + +* `global_token_budgets` — power-of-2 multiples of `global_token_per_image` (e.g., `[272, 544, 1088, 2176, 4352, 8704, 13824]` for DeepSeek-OCR). +* `local_token_budgets` — power-of-2 multiples of `local_token_per_patch` (e.g., `[0, 100, 200, 400, 800, 1600, 3200, 6400, 12800]` for DeepSeek-OCR). A budget of `0` is always included to handle images with no local patches (images ≤ 640×640 that produce only global features). + +Both lists are capped at the same `max_budget`. + +**Dual-path greedy packing.** Each `EncoderItemSpec` provides both `global_output_tokens` (constant per image) and `local_output_tokens` (proportional to the patch count). The dual-path packing algorithm constrains both budgets simultaneously: + +* Sort images by total output tokens (global + local), smallest first. +* Greedily pack images: an image is added to the current sub-batch only if both the accumulated global tokens ≤ `max_global_budget` **and** the accumulated local tokens ≤ `max_local_budget`, with the image count ≤ `max_batch_size`. +* Once either constraint would overflow, finalize the sub-batch and find the smallest fitting budget **independently** for each path. +* Repeat until all images are packed. + +**Partial graph fallback.** After packing, each sub-batch falls into one of four execution scenarios: + +| Global budget | Local budget | Execution | +| :---: | :---: | --- | +| Found | Found | Both paths use CUDA graph replay | +| Found | `None` | Global graph replay + local path skipped (no patches) | +| `None` | Found | Global eager fallback + local graph replay | +| `None` | `None` | Both paths fall back to eager execution | + +Note that the `0`-budget graph is never actually replayed for local — it signals that local patch processing should be skipped entirely. + +**Buffer keys per path.** Global and local paths use different buffer keys. For DeepSeek-OCR, the global path uses `pixel_values` (full images, shape `[B, 3, 1280, 1280]`) while the local path uses `images_crop` (patches, shape `[P, 3, 1024, 1024]`). The manager iterates over each captured graph's own `input_buffers.keys()` rather than a shared `buffer_keys` list, so both paths can use different buffers. + +**Post-processing.** The `postprocess_encoder_output` method receives a `local_output` parameter (a tensor or `None`) containing the local-path encoder output. The model is responsible for assembling global and local features into the final per-image embedding. For DeepSeek-OCR, this means reshaping the global output into `[B, 272, n_embed]`, the local output into `[P, 100, n_embed]`, assembling patch grids with newline tokens, and concatenating `[patches_grid, global, view_separator]` for each image. + +!!! note + The dual-path design enables partial CUDA graph coverage — one path can hit while the other falls back to eager. This avoids wasted compute on zero-padded patch buffers for untiled images and avoids graph invalidation caused by variable `crop_shape` per image. + ### Data-parallel support When `mm_encoder_tp_mode="data"`, the manager distributes images across TP ranks using load-balanced assignment via `get_load_balance_assignment`, executes locally on each rank, then gathers results back in the original order via `tensor_model_parallel_all_gather`. @@ -67,29 +111,31 @@ Models opt-in to encoder CUDA Graphs by implementing the [SupportsEncoderCudaGra * `get_encoder_cudagraph_config()` — returns static configuration (supported modalities, buffer keys, output hidden size, padding logics, max frames per video). * `get_encoder_cudagraph_budget_range(vllm_config)` — returns `(min_budget, max_budget)` for auto-inference of token budgets. -* `get_encoder_cudagraph_item_specs(mm_kwargs)` — returns `list[EncoderItemSpec]` describing each item with its input size and output token count. Replaces the former three separate methods (`get_num_items`, `get_per_item_output_tokens`, `get_per_item_input_sizes`). +* `get_encoder_cudagraph_item_specs(mm_kwargs)` — returns `list[EncoderItemSpec]` describing each item with its input size, total output token count (`output_tokens`), and optionally per-path token counts (`global_output_tokens`, `local_output_tokens`) for dual-path models. * `select_encoder_cudagraph_items(mm_kwargs, indices)` — extracts a sub-batch of items by index, used during greedy packing and DP sharding. -* `prepare_encoder_cudagraph_capture_inputs(...)` — creates dummy inputs for graph capture. Returns `EncoderCudaGraphCaptureInputs` with a single `values: dict[str, torch.Tensor]` that contains all buffers to be recorded into the graph. -* `prepare_encoder_cudagraph_replay_buffers(mm_kwargs, max_batch_size, max_frames_per_batch)` — computes buffer values from actual batch inputs. Returns `EncoderCudaGraphReplayBuffers` with a `values` dict whose keys match `buffer_keys` in the config. -* `encoder_cudagraph_forward(inputs: dict[str, torch.Tensor])` — forward pass accepting only fixed-shaped input tensors (the captured `values` dict). Called during both capture and replay. The `pixel_values` tensor is included in `inputs` alongside metadata buffers. -* `encoder_eager_forward(mm_kwargs)` — fallback eager forward when no graph fits. -* `postprocess_encoder_output(...)` — post-process encoder output, delegates to `scatter_output_slices` by default. +* `prepare_encoder_cudagraph_capture_inputs(..., path="default")` — creates dummy inputs for graph capture. The `path` parameter (`"global"` or `"local"`) tells the model which path to generate dummy inputs for. Returns `EncoderCudaGraphCaptureInputs` with a single `values: dict[str, torch.Tensor]` that contains all buffers to be recorded into the graph. +* `prepare_encoder_cudagraph_replay_buffers(mm_kwargs, max_batch_size, max_frames_per_batch, path="default")` — computes buffer values from actual batch inputs. The `path` parameter selects which modality keys to extract from `mm_kwargs`. Returns `EncoderCudaGraphReplayBuffers` with a `values` dict whose keys match the captured graph's `input_buffers.keys()`. +* `encoder_cudagraph_forward(inputs: dict[str, torch.Tensor], path="default")` — forward pass accepting only fixed-shaped input tensors (the captured `values` dict). Called during both capture and replay. The `path` parameter dispatches to the correct encoder sub-module (e.g., global vs. local path for DeepSeek-OCR). +* `encoder_eager_forward(mm_kwargs, path="default")` — fallback eager forward when no graph fits. When `path` is `"global"` or `"local"`, runs only that encoder path without graph capture. +* `postprocess_encoder_output(..., local_output=None)` — post-process encoder output. The `local_output` parameter receives the local-path encoder output tensor (or `None`), enabling dual-path models to assemble global and local features into the final per-image embedding. !!! note The `SupportsEncoderCudaGraph` protocol is designed to be model-agnostic. New vision encoder models can opt-in by implementing the protocol methods without modifying the manager. **Supported models:** -| Architecture | Models | CG for Image | CG for Video | -| ------------ | ------ | ------------ | ------------ | -| `Llama4ForConditionalGeneration` | `Llama 4` | ✅︎ | - | -| `InternVLChatModel` | `InternVL3.5`, `InternVL3`, `InternVL2.5`, `InternVL2` | ✅︎ | ✅︎ | -| `Qwen2VLForConditionalGeneration` | `Qwen2-VL` | ✅︎ | ✅︎ | -| `Qwen2_5_VLForConditionalGeneration` | `Qwen2.5-VL` | ✅︎ | ✅︎ | -| `Qwen3VLForConditionalGeneration` | `Qwen3-VL` | ✅︎ | ✅︎ | -| `Qwen3_5ForConditionalGeneration` | `Qwen3.5` | ✅︎ | ✅︎ | -| `Step3VLForConditionalGeneration` | `Step3-VL` | ✅︎ | ❌︎ | -| `Glm4vForConditionalGeneration` | `GLM-4.1V, GLM-4.6V-Flash` | ✅︎ | ✅︎ | +| Architecture | Models | CG for Image | CG for Video | Dual-Path Graph | +| ------------ | ------ | ------------ | ------------ | --------------- | +| `DeepseekOCRForCausalLM` | `DeepSeek-OCR` | ✅︎ | ❌︎ | ✅︎ | +| `Glm4vForConditionalGeneration` | `GLM-4.1V, GLM-4.6V-Flash` | ✅︎ | ✅︎ | ❌︎ | +| `InternVLChatModel` | `InternVL3.5`, `InternVL3`, `InternVL2.5`, `InternVL2` | ✅︎ | ✅︎ | ❌︎ | +| `KimiVLForConditionalGeneration` | `Kimi-VL` | ✅︎ | ❌︎ | ❌︎ | +| `Llama4ForConditionalGeneration` | `Llama 4` | ✅︎ | ❌︎ | ❌︎ | +| `Qwen2VLForConditionalGeneration` | `Qwen2-VL` | ✅︎ | ✅︎ | ❌︎ | +| `Qwen2_5_VLForConditionalGeneration` | `Qwen2.5-VL` | ✅︎ | ✅︎ | ❌︎ | +| `Qwen3VLForConditionalGeneration` | `Qwen3-VL` | ✅︎ | ✅︎ | ❌︎ | +| `Qwen3_5ForConditionalGeneration` | `Qwen3.5` | ✅︎ | ✅︎ | ❌︎ | +| `Step3VLForConditionalGeneration` | `Step3-VL` | ✅︎ | ❌︎ | ❌︎ | !!! note Encoder CUDA Graphs have currently been tested with `--mm-encoder-attn-backend=FLASH_ATTN` and `--mm-encoder-attn-backend=FLASHINFER` on Blackwell GPUs. @@ -104,6 +150,8 @@ Three fields in `CompilationConfig` control encoder CUDA Graphs: * `encoder_cudagraph_max_vision_items_per_batch` (`int`, default `0`) — maximum number of images/videos per batch during capture. If 0 (default), auto-inferred as `max_budget // min_budget`. * `encoder_cudagraph_max_frames_per_batch` (`int`, default `None`) — maximum number of video frames per batch during capture. If `None` (default), auto-inferred as `encoder_cudagraph_max_vision_items_per_batch * max_frames_per_video` (`max_frames_per_video` is a model-specific value from `EncoderCudaGraphConfig`, computed by `get_max_frames_per_video()` on the model). If we limit the video count per prompt to `0`, it will also be set to `0` (i.e., fall back to image-only mode). +Dual-path mode is configured at the model level via `EncoderCudaGraphConfig` fields (`enable_dual_path_graph`, `global_token_per_image`, `local_token_per_patch`) — no additional user configuration is required. The manager automatically generates separate budget lists and routes to dual-path execution when the model opts in. + ## Usage guide ### Image inference diff --git a/docs/design/nixl_kv_push_connector.md b/docs/design/nixl_kv_push_connector.md new file mode 100644 index 000000000000..b99ba6659f74 --- /dev/null +++ b/docs/design/nixl_kv_push_connector.md @@ -0,0 +1,256 @@ +# NIXL push-mode KV transfer + +The default NIXL connector is **pull-based**: the decode (D) instance +reads KV blocks from the prefill (P) instance via `NIXL READ` after +prefill completes. `NixlPushConnector` adds a **push-based** alternative +in which P writes the KV blocks directly into D's pre-allocated memory +via `NIXL WRITE`. + +This document describes the threading, queues, and scheduling +interactions specific to the push design. The pull-mode design is +unchanged; the push connector reuses the same handshake, NIXL agent +setup, and metadata path wherever possible. + +## High-level flow + +```mermaid +sequenceDiagram + autonumber + participant Client + participant Proxy + participant DSched as D Scheduler + participant DWorker as D Worker (main) + participant DWriter as D Writer + participant PWriter as P Writer + participant PWorker as P Worker (main) + participant PSched as P Scheduler + + Client->>Proxy: POST /v1/completions + Proxy->>PSched: prefill leg (do_remote_decode=True, max_tokens=1) + Proxy->>DSched: decode leg (do_remote_prefill=True, P coordinates) + + note over DSched,DWriter: D side - register blocks with P + DSched->>DSched: update_state_after_alloc, stash registration, arm watchdog + DSched->>DWorker: build_connector_meta -> meta.push_registrations + DWorker->>DWriter: enqueue (req_id, reg_data) on _reg_send_inbox + DWriter->>PWriter: NIXL send_notif PUSH_REG msgpack + + note over PSched,PWriter: P side - prefill, stage finished blocks + PSched->>PSched: request_finished, stash blocks + PSched->>PWorker: build_connector_meta -> meta.push_finished_blocks + PWorker->>PWriter: enqueue (req_id, blocks) on _finished_blocks_inbox + + note over PWriter: P writer matches and WRITEs + PWriter->>PWriter: get_new_notifs returns PUSH_REG, route via _handle_push_reg_notif + alt PUSH_REG and finished blocks both present + PWriter->>PWriter: pop matching pair, fire WRITE + else only one side present + PWriter->>PWriter: stash and wait, self-poll only when blocks unmatched + end + PWriter->>PWriter: ensure D handshake (one-time) + PWriter->>DWriter: NIXL WRITE direct to D GPU + completion notif + + note over DWorker,DWriter: D side - completion accounting + DWriter-->>DWorker: forward HB and completion notifs via _pending_completion_notifs + DWorker->>DWorker: _get_new_notifs drains, HB extends lease, completion marks recv done + DWorker->>DSched: update_connector_output(finished_recving) + DSched->>DSched: clear watchdog deadline + + note over PWorker,PWriter: P side - reclaim + PWorker->>PWorker: get_finished, drain _sending_transfers, queue eviction + PWriter->>PWriter: drain _evict_finished_inbox, drop stale state + PWorker->>PSched: update_connector_output(finished_sending) + PSched->>PSched: free lease + + DWorker-->>Proxy: stream decode tokens + Proxy-->>Client: response +``` + +## Threads + +``NixlPushConnectorWorker`` introduces a single dedicated background +thread per worker (i.e. per TP rank), named ``nixl-push-writer``. +Each owns the new push-specific NIXL operations on its rank: + +* ``nixl_wrapper.get_new_notifs()`` — receive notifications. +* ``nixl_wrapper.send_notif(...)`` for the ``PUSH_REG:`` (D + side) and for the per-WRITE completion notif (P side). +* ``nixl_wrapper.make_prepped_xfer(...) / transfer(...)`` — submit the + WRITE itself. + +Heartbeats continue to go out from the engine main thread via the +existing base-worker ``_send_heartbeats`` plumbing inside +``start_load_kv``. + +### Wake model + +The writer thread blocks on ``_push_writer_wake`` (a +``threading.Event``) when it has no work. Three callers set the +event: + +1. **``start_load_kv``** (worker main thread, called once per engine + step with the scheduler's metadata) — sets the wake only when the + step actually hands the writer new work, i.e. when + ``meta.push_registrations`` or ``meta.push_finished_blocks`` is + non-empty. This is the wake for new transfers. +2. **``get_finished``** (worker main thread, called once per engine + step to report completions) — always sets the wake. The writer is + the sole consumer of ``nixl_wrapper.get_new_notifs()`` for push, + so this gives it a chance to drain inbound notifs (heartbeats from + D, completion notifs after a WRITE, late-arriving ``PUSH_REG``) + even when there is no new metadata to act on. +3. **Handshake-completion callback** (background handshake executor + thread) — when a deferred D→P handshake finishes successfully, the + future's done-callback re-enqueues the registration onto + ``_reg_send_inbox`` and sets the wake so the corresponding + ``send_notif`` runs on the writer (we never call ``send_notif`` from + the executor thread). On this second pass ``_ensure_handshake`` + returns ``None`` (the agent is now connected), so the writer sends + the ``PUSH_REG`` directly. If the handshake *failed*, the callback + fails the request instead of re-enqueuing, so there is no retry + loop. + +In addition to event-driven wakes, the writer self-polls at +``_PUSH_WRITER_POLL_INTERVAL_MS = 1.0`` ms while there are P-side +finished blocks waiting for an unmatched ``PUSH_REG``. + +When a request completes on P (lease expires or the WRITE finishes), +``get_finished`` enqueues the request id onto ``_evict_finished_inbox``, +which the writer drains to drop stale ``_push_finished_blocks`` / +``_pending_d_registrations`` and stop self-polling. + +## Writer-local matching tables + +| Table | Owner | Holds | +|--------------------------------|------------------|------------------------------------------------------------------------| +| `_pending_d_registrations` | writer | D registrations received from a remote D, waiting for P's blocks | +| `_push_finished_blocks` | writer | P blocks staged by the scheduler, waiting for a remote D registration | + +Either side can arrive first. The writer matches in both directions: +when a ``PUSH_REG`` arrives we look up ``_push_finished_blocks``, and +when finished blocks arrive we look up ``_pending_d_registrations``. +Both lookups try an exact ``request_id`` match first, then fall back +to comparing the ids after stripping the trailing per-engine random +suffix (via ``get_base_request_id``). The fallback exists because the +proxy hands the same ``X-Request-Id`` to both legs, so P and D wrap it +into the same ``cmpl--`` form and differ only by the +8-hex randomization suffix that ``input_processor.assign_request_id`` +appends per engine. Stripping just that suffix normalizes both sides +to the same id while preserving the completion index (so multi-prompt +sub-requests stay distinct). It also works whether or not +``VLLM_DISABLE_REQUEST_ID_RANDOMIZATION`` is set, which matters since +that env var is slated for removal upstream. + +## Wire format + +A push registration is sent as a NIXL notification: + +```text +PUSH_REG: +``` + +Fields in the dict: + +| Field | Set by | Meaning | +|----------------------|--------|------------------------------------------------------------------------| +| ``request_id`` | D | D's own vLLM request id; P's match key, echoed in the completion notif | +| ``decode_engine_id`` | D | D's engine id (P uses this for the reverse handshake) | +| ``decode_host`` | D | D's NIXL side-channel host | +| ``decode_port`` | D | D's NIXL side-channel port | +| ``decode_tp_size`` | D | D's tensor-parallel size | +| ``local_block_ids`` | D | per-group lists of D's *logical* block ids (preallocated) | +| ``remote_engine_id`` | D | P's engine id (for the existing P-side handshake) | +| ``remote_host`` | D | P's NIXL side-channel host | +| ``remote_port`` | D | P's NIXL side-channel port | +| ``remote_tp_size`` | D | P's tensor-parallel size | + +D ships **logical** block ids; P expands them to physical block ids at +WRITE-submission time using the ratio learned during the NIXL +handshake (`remote_physical_blocks_per_logical`). This matches the +pull-mode contract — schedulers ship logical ids, workers expand to +physical at submission. + +The completion notif sent from P to D after a WRITE is the existing +`:` format used in pull mode (here ``request_id`` +is D's own request id, taken from the registration), so the D-side +accounting code is unchanged. + +## Scheduler-side responsibilities + +`NixlPushConnectorScheduler` extends the base scheduler with: + +* **D side** — `update_state_after_alloc` stashes registration data in + `_push_pending_registrations` and arms a soft watchdog + (`_push_registration_deadlines`). `build_connector_meta` drains the + stash into `meta.push_registrations` and any expired entries are + dropped with a warning. +* **P side** — `request_finished` stashes block IDs in + `_finished_request_blocks` (for the lease and for + `has_pending_push_work`) and `_newly_finished_push_blocks` (for the + next worker step via `meta.push_finished_blocks`). +* **Both sides** — `has_pending_push_work` keeps the engine main loop + stepping while there is in-flight push state, so the writer always + gets at least one wake per step. + +`update_connector_output`: + +* `finished_sending` (P side) clears the lease entry. +* `finished_recving` (D side) clears the watchdog deadline. + +## Timeouts and watchdogs + +Two per-request timers are armed on the scheduler: + +* **D-side registration watchdog** — ``_push_registration_deadlines``. + If a registered request does not see a push completion within + ``push_registration_timeout`` seconds (defaults to + ``decoder_kv_blocks_ttl``), ``build_connector_meta`` drops the stale + registration and the pending entry, logs a warning, and stops trying + to resend the registration. The corresponding request remains tracked + in ``_reqs_need_recv``; it is the engine's request-level abort path + (or the user / proxy timing out the HTTP call) that ultimately fails + the request. +* **P-side block lease** — same ``_kv_lease_duration`` used by pull + mode. ``request_finished`` sets the expiration in ``_reqs_need_send`` + and ``update_connector_output(finished_sending=...)`` clears it on + successful WRITE. Stale leases are reaped by ``get_finished`` in the + base worker, which then enqueues the eviction onto + ``_evict_finished_inbox`` so the writer also stops self-polling. + +## Failure handling + +* **D-side handshake failure (P→D handshake before sending PUSH_REG)** — + the future's done-callback calls ``_handle_failed_transfer(rid, None)``, + which marks D's pre-allocated blocks invalid and enqueues onto + ``_failed_recv_reqs`` so the next ``get_finished`` reports the + request as a failed recv. Same recv-side accounting as pull mode. +* **D-side ``send_notif`` failure when shipping the PUSH_REG to P** — + identical handling: ``_handle_failed_transfer`` marks the recv as + failed. +* **P-side WRITE submission failure** — the WRITE handle (if any) is + released and ``xfer_stats.record_failed_transfer()`` bumps the + failure counter. We deliberately do not call + ``_handle_failed_transfer`` here: ``req_id`` on the P side has no + entry in ``_recving_metadata`` (P is not the receiver), so the + helper would put a P-local request id into ``_failed_recv_reqs`` + and trip the assertion in the base worker's ``get_finished``. The + outbound WRITE is dropped on the floor; D's lease watchdog handles + the missing completion. + +## Summary + +The push design is a small, well-contained extension on top of the +existing NIXL connector: + +* one new connector class, one new scheduler class, one new worker + class — all subclasses of the existing base classes; +* one dedicated background thread per worker; +* a few cross-thread queues, each with a single consumer (the writer); + most have one producer, except ``_reg_send_inbox``, which is fed both + by the engine main thread (new registrations) and by the + handshake-completion callback (registrations replayed after their + D→P handshake finishes); +* one new notification type (`PUSH_REG:`). + +Behavior on the engine main thread is otherwise unchanged. The writer +thread is event-driven and idle when there is no push work. diff --git a/docs/features/kv_offloading_usage.md b/docs/features/kv_offloading_usage.md index 39b826bfd565..93da2ed0361a 100644 --- a/docs/features/kv_offloading_usage.md +++ b/docs/features/kv_offloading_usage.md @@ -127,6 +127,29 @@ PYTHONHASHSEED=0 vllm serve ... - FS thread counts: tune `n_read_threads` and `n_write_threads` to the parallelism your storage can sustain. Reads are latency-sensitive on the prefill path, so prefer more read threads when prefill hit rates are high. - Sharing `root_dir` across runs: runs with the same model, `block_size`, parallelism layout, and dtype share files under the same `` subdirectory. Changing any of these produces a new subdirectory; old ones are orphaned but harmless. Delete them to reclaim disk. +## Per-Request Selective Offload + +Individual requests can cap how many of their tokens are eligible for offload by setting `max_offload_tokens` in the request's `kv_transfer_params`. Only the first `max_offload_tokens` tokens of the request are offloaded; blocks beyond that point are skipped on the store path. This is useful when a known prefix (e.g., a system prompt or shared context) is worth caching but later request-specific tokens are not. + +| Key | Type | Notes | +| --- | --- | --- | +| `max_offload_tokens` | non-negative `int` | Upper bound on tokens to offload for this request. `0` disables offload for the request entirely; omit the key (or set to `None`) for no cap. Non-`int`, negative, or `bool` values are rejected with a warning and treated as no cap. | + +!!! note + `max_offload_tokens` is experimental and subject to change. + +Example (OpenAI-compatible completions request): + +```json +{ + "model": "", + "prompt": "...", + "kv_transfer_params": { + "max_offload_tokens": 1024 + } +} +``` + ## Further Reading - [vLLM blog: KV Offloading Connector](https://vllm.ai/blog/2026-01-08-kv-offloading-connector) — motivation, architecture (DMA-based async transfer), and benchmarks (TTFT and throughput). diff --git a/docs/features/mooncake_store_connector_usage.md b/docs/features/mooncake_store_connector_usage.md index f23acae10c4f..bab69410978f 100644 --- a/docs/features/mooncake_store_connector_usage.md +++ b/docs/features/mooncake_store_connector_usage.md @@ -205,6 +205,7 @@ the vLLM JSON config. - `load_async` (bool): Enable asynchronous loading for better compute-I/O overlap. Default: `true`. - `enable_cross_layers_blocks` (bool): Enable cross-layer block packing for reduced store operations. Default: `false`. - `lookup_rpc_port` (int): Custom port for the ZMQ lookup RPC socket. Default: `0`. +- `cache_prefix` (str): Namespace prepended to every store key. Lets separate deployments share one Mooncake master without polluting each other — instances configured with different prefixes never see each other's cached blocks, even for identical prompts. All instances that should share a prefix cache must use the same value. Default: `""` (no prefix; keys are byte-identical to the unprefixed format). ## Notes diff --git a/docs/features/nixl_connector_usage.md b/docs/features/nixl_connector_usage.md index 8ab29b438883..03b05751c14d 100644 --- a/docs/features/nixl_connector_usage.md +++ b/docs/features/nixl_connector_usage.md @@ -423,6 +423,54 @@ To enable this feature: --kv-transfer-config '{..., "kv_connector_extra_config": {"enable_cross_layers_blocks": "True"}}' ``` +## Metrics Reference + +vLLM periodically logs a `KV Transfer metrics` line summarising NIXL transfer +activity for the last reporting interval. Example output: + +```text +KV Transfer metrics: Num successful transfers=4, Avg xfer time (ms)=1.381, +P90 xfer time (ms)=2.601, Avg post time (ms)=0.672, P90 post time (ms)=0.801, +Avg MB per transfer=2.25, Throughput (MB/s)=1629.549, Avg number of descriptors=72.0 +``` + +The table below describes each field. All timing values cover only the +successful transfers recorded in the current interval; failed transfers are +counted separately via Prometheus (see +[Prometheus metrics](#prometheus-metrics) below). + +| Metric | Unit | Description | +| -------- | ------ | ------------- | +| `Num successful transfers` | count | Number of NIXL KV-block transfers that completed without error during the interval. A transfer corresponds to one prefill request's worth of KV cache being moved from the prefiller to the decoder (or vice versa in bidirectional mode). | +| `Avg xfer time (ms)` | ms | Mean end-to-end transfer duration (`xferDuration` in NIXL telemetry, converted from µs). Measured from when the request is posted to when the backend reports completion, so it includes both the posting step and the actual data movement. | +| `P90 xfer time (ms)` | ms | 90th-percentile transfer duration. Use this to identify tail latency: a large gap between average and P90 suggests occasional stragglers (e.g., network congestion or large KV blocks). | +| `Avg post time (ms)` | ms | Mean time to submit the transfer request to the RDMA backend (`postDuration` in NIXL telemetry). This is the synchronous cost of posting work to the NIC queue (descriptor setup, etc.) before the async data movement begins. | +| `P90 post time (ms)` | ms | 90th-percentile request-posting duration. Elevated P90 here (with low xfer P90) points to overhead in submitting requests rather than in the data transfer itself. | +| `Avg MB per transfer` | MB | Mean payload size per transfer, computed as `total bytes transferred / number of transfers`. Reflects the average KV cache footprint of a single request (sequence length × layers × head dimension × dtype bytes). | +| `Throughput (MB/s)` | MB/s | Effective bandwidth over the interval: `total MB transferred / total xfer time (s)` across all successful transfers. This is aggregate throughput, not per-request bandwidth. | +| `Avg number of descriptors` | count | Mean number of NIXL memory descriptors (scatter-gather segments) submitted per transfer. More descriptors indicate more fragmented or larger KV cache allocations; very high counts can increase descriptor-registration overhead. | + +### Prometheus metrics + +In addition to the periodic log line, the following Prometheus metrics are +exported when NixlConnector is active: + +| Metric name | Type | Description | +| ------------- | ------ | ------------- | +| `vllm:nixl_xfer_time_seconds` | Histogram | Per-transfer RDMA copy duration (seconds). | +| `vllm:nixl_post_time_seconds` | Histogram | Time to submit the transfer request to the RDMA backend (seconds). | +| `vllm:nixl_bytes_transferred` | Histogram | Bytes moved per transfer. | +| `vllm:nixl_num_descriptors` | Histogram | Descriptor count per transfer. | +| `vllm:nixl_num_failed_transfers` | Counter | Cumulative count of failed NIXL KV-block transfers. | +| `vllm:nixl_num_failed_notifications` | Counter | Cumulative count of failed completion notifications (`send_notif`). | +| `vllm:nixl_num_kv_expired_reqs` | Counter | Requests whose KV blocks expired on the prefiller before the decoder read them (tracked on the P instance). | + +!!! tip + High `vllm:nixl_num_kv_expired_reqs` indicates that the prefiller's lease + duration (`kv_lease_duration`) is too short for your network or workload. + Increase it via `--kv-transfer-config '{"kv_connector_extra_config": + {"kv_lease_duration": }}'`. + ## Example Scripts/Code Refer to these example scripts in the vLLM repository: diff --git a/docs/features/quantization/README.md b/docs/features/quantization/README.md index 2be357d8860d..69ece3607610 100644 --- a/docs/features/quantization/README.md +++ b/docs/features/quantization/README.md @@ -9,7 +9,6 @@ The following are the supported quantization formats for vLLM: - [AutoAWQ](auto_awq.md) - [BitsAndBytes](bnb.md) -- [GGUF](gguf.md) - [GPTQModel](gptqmodel.md) - [Intel Neural Compressor](inc.md) - [LLM Compressor](llm_compressor/README.md) diff --git a/docs/features/quantization/gguf.md b/docs/features/quantization/gguf.md index 41912a506014..0aa76d679e15 100644 --- a/docs/features/quantization/gguf.md +++ b/docs/features/quantization/gguf.md @@ -3,8 +3,14 @@ !!! warning Please note that GGUF support in vLLM is highly experimental and under-optimized at the moment, it might be incompatible with other features. Currently, you can use GGUF as a way to reduce memory footprint. If you encounter any issues, please report them to the vLLM team. -!!! warning - Currently, vllm only supports loading single-file GGUF models. If you have a multi-files GGUF model, you can use [gguf-split](https://github.com/ggerganov/llama.cpp/pull/6135) tool to merge them to a single-file model. +!!! note + GGUF support has migrated to OOT [vllm-gguf-plugin](https://github.com/vllm-project/vllm-gguf-plugin). Make sure you have GGUF plugin installed before serving a GGUF model. + +Before serving a GGUF model, make sure to install the [vllm-gguf-plugin](https://github.com/vllm-project/vllm-gguf-plugin): + +```bash +uv pip install vllm-gguf-plugin +``` To run a GGUF model with vLLM, you can use the `repo_id:quant_type` format to load directly from HuggingFace. For example, to load a Q4_K_M quantized model from [unsloth/Qwen3-0.6B-GGUF](https://huggingface.co/unsloth/Qwen3-0.6B-GGUF): diff --git a/docs/features/speculative_decoding/README.md b/docs/features/speculative_decoding/README.md index 58d1df9dced0..7213ef41ecd0 100644 --- a/docs/features/speculative_decoding/README.md +++ b/docs/features/speculative_decoding/README.md @@ -17,6 +17,7 @@ vLLM supports a variety of methods of speculative decoding. Model-based methods - [Suffix Decoding](suffix.md) - [Hidden State Extraction](extract_hidden_states.md) - [Custom Proposer Backend (Experimental)](#custom-proposer-backend-experimental) +- [Dynamic Speculative Decoding](dynamic_speculative_decoding.md) ## Method Selection at a Glance @@ -33,6 +34,7 @@ depend on your model family, traffic pattern, hardware, and sampling settings. | N-gram | Low to medium gain | Medium gain | Lightweight and easy to enable. | | Suffix decoding | Low to medium gain | Medium gain | No extra draft model; dynamic speculation depth. | | Custom Proposer | Varies | Varies | Bring your own proposer class (experimental). | +| Dynamic Speculative Decoding | High gain | Higher than base SD method | Useful for RL or workload with fluctuating QPS | For reproducible measurements in your environment, use [`examples/features/speculative_decoding/spec_decode_offline.py`](../../../examples/features/speculative_decoding/spec_decode_offline.py) diff --git a/docs/features/speculative_decoding/dynamic_speculative_decoding.md b/docs/features/speculative_decoding/dynamic_speculative_decoding.md new file mode 100644 index 000000000000..eecf789d6dca --- /dev/null +++ b/docs/features/speculative_decoding/dynamic_speculative_decoding.md @@ -0,0 +1,78 @@ +# Dynamic Speculative Decoding + +## Why is Dynamic SD needed? + +SD methods need to verify K tokens for each sequence during decoding. As BS increases, the effective BS becomes BS\*K which increases the compute requirement during verification. When this BS\*K goes beyond a critical BS then SD negatively impacts the decode speed (TPOT). DSD helps by tuning the K to an optimal value such that we continue to reap the benefits from SD. + +## Use cases + +* Variable concurrency workload using same deployment. K would decrease as concurrency increases. +* During RL rollout where we start off with high BS but then end up with small BS due to very few long tail request which end up generating a lot of tokens stalling the progress of the current rollout. Here K would go up during the end of rollout. + +## `--speculative-config` schema + +To use Dynamic SD, add `num_speculative_tokens_per_batch_size` to the config of an SD method which is a list of list. Here, an entry is `[start_bs, end_bs, optimal_K]` which means when the concurrency is within range `[start_bs, end_bs]` then `optimal_K` number of draft tokens are used. For e.g., + +```bash +--speculative-config '{ + "method": "eagle", + "model": "yuhuili/EAGLE-LLaMA3.1-Instruct-8B", + "num_speculative_tokens": 3, + "num_speculative_tokens_per_batch_size": [ + [1, 64, 3], + [65, 128, 1], + [129, 512, 0] + ] + }' +``` + +implies that: + +* K=3 will be used when the concurrency is in range [1, 64] +* K=1 will be used when the concurrency is in range [65, 128] +* K=0 will be used when the concurrency is in range [129, 512], i.e., no draft tokens will be produced. + +## Online Examples + +### Dynamic SD Eagle Drafter + +```bash +VLLM_USE_V2_MODEL_RUNNER=0 vllm serve meta-llama/Llama-3.1-8B-Instruct \ + --speculative-config '{ + "method": "eagle", + "model": "yuhuili/EAGLE-LLaMA3.1-Instruct-8B", + "num_speculative_tokens": 3, + "num_speculative_tokens_per_batch_size": [ + [1, 64, 3], + [65, 128, 1], + [129, 512, 0] + ] + }' +``` + +### Dynamic SD Eagle3 Drafter + +```bash +VLLM_USE_V2_MODEL_RUNNER=0 vllm serve meta-llama/Llama-3.1-8B-Instruct \ + --speculative-config '{ + "method": "eagle3", + "model": "yuhuili/EAGLE3-LLaMA3.1-Instruct-8B", + "num_speculative_tokens": 3, + "num_speculative_tokens_per_batch_size": [ + [1, 16, 5], + [17, 32, 4], + [33, 64, 3], + [65, 128, 1], + [129, 512, 0] + ] + }' + +``` + +## Limitations + +* only tested with Eagle and Eagle-3. Other SD methods may or may not work out of the box +* only usable with Model Runner V1 +* not compatible with full cuda graph so we force piece-wise cuda graph with this feature + +We are working on enabling it on MRv2 with full cuda graph support. diff --git a/docs/features/tool_calling.md b/docs/features/tool_calling.md index d1a56e83cd4c..1d10a94c7123 100644 --- a/docs/features/tool_calling.md +++ b/docs/features/tool_calling.md @@ -109,24 +109,30 @@ vLLM supports the `tool_choice='none'` option in the chat completion API. When t ## Constrained Decoding Behavior -Whether vLLM enforces the tool parameter schema during generation depends on the `tool_choice` mode: +Whether vLLM enforces the tool parameter schema during generation depends on the `tool_choice` mode and the per-tool `strict` field: | `tool_choice` value | Schema-constrained decoding | Behavior | | --- | --- | --- | | Named function | Yes (via structured outputs backend) | Arguments are guaranteed to be valid JSON conforming to the function's parameter schema. | | `"required"` | Yes (via structured outputs backend) | Same as named function. The model must produce at least one tool call. | -| `"auto"` | No | The model generates freely. A tool-call parser extracts tool calls from the raw text. Arguments may be malformed or not match the schema. | +| `"auto"` | Only when `strict: true` is set on at least one tool | Structural-tag parsers constrain tool-call arguments when a tool opts in with `strict: true`. Without it, the model generates freely and tool calls are extracted from raw text. | | `"none"` | N/A | No tool calls are produced. | -When schema conformance matters, prefer `tool_choice="required"` or named function calling over `"auto"`. +### Strict Mode -### Strict Mode (`strict` parameter) +For `tool_choice="required"` or named function calling, structural-tag constraints are always applied regardless of the `strict` field. For `tool_choice="auto"`, setting `strict: true` on at least one tool opts in to structural-tag constraints; without it, the model generates freely and tool calls are extracted from raw text. The `strict` field is supported across all three API surfaces: Chat Completion, Responses, and Anthropic Messages. -The [OpenAI API](https://platform.openai.com/docs/guides/function-calling#strict-mode) supports a `strict` field on function definitions. When set to `true`, OpenAI uses constrained decoding to guarantee that tool-call arguments match the function schema, even in `tool_choice="auto"` mode. +For best compatibility with strict schema enforcement, define tool parameter schemas in the OpenAI strict-schema style: -vLLM **does not implement** `strict` mode today. The `strict` field is accepted in requests (to avoid breaking clients that set it), but it has no effect on decoding behavior. In auto mode, argument validity depends entirely on the model's output quality and the parser's extraction logic. +* Set `additionalProperties` to `false` for each object in `parameters`. +* Mark all fields in `properties` as required. +* Represent optional fields by allowing `null`, for example `{"type": ["string", "null"]}`. -Tracking issues: [#15526](https://github.com/vllm-project/vllm/issues/15526), [#16313](https://github.com/vllm-project/vllm/issues/16313). +vLLM also provides a global toggle via the `VLLM_ENFORCE_STRICT_TOOL_CALLING` environment variable (defaults to `true`). When set to `false`, vLLM does not attach structural tags for tool calling regardless of the per-tool `strict` field. This environment variable only affects structural-tag based tool calling; it does not change schema-derived structured outputs used by named function calling or `tool_choice="required"`. + +```bash +VLLM_ENFORCE_STRICT_TOOL_CALLING=false vllm serve ... +``` ## Automatic Function Calling @@ -146,7 +152,7 @@ from HuggingFace; and you can find an example of this in a `tokenizer_config.jso If your favorite tool-calling model is not supported, please feel free to contribute a parser & tool use chat template! !!! note - With `tool_choice="auto"`, tool-call arguments are extracted from the model's raw text output by the selected parser. No schema-level constraint is applied during decoding, so arguments may occasionally be malformed or violate the function's parameter schema. See [Constrained Decoding Behavior](#constrained-decoding-behavior) for details. + With `tool_choice="auto"`, schema-level constraint requires both `VLLM_ENFORCE_STRICT_TOOL_CALLING=true` (the default) and at least one tool with `strict: true`. When these conditions are met and the selected parser supports structural tags, vLLM constrains tool-call arguments. Otherwise, vLLM extracts tool calls from raw text, so arguments may occasionally be malformed or violate the function's parameter schema. ### Hermes Models (`hermes`) diff --git a/docs/getting_started/installation/cpu.arm.inc.md b/docs/getting_started/installation/cpu.arm.inc.md index f01ba429ee03..7a783b53c65f 100644 --- a/docs/getting_started/installation/cpu.arm.inc.md +++ b/docs/getting_started/installation/cpu.arm.inc.md @@ -96,8 +96,8 @@ cd vllm_source Third, install required dependencies: ```bash -uv pip install -r requirements/build/cpu.txt --torch-backend cpu -uv pip install -r requirements/cpu.txt --torch-backend cpu +uv pip install -r requirements/build/cpu.txt --torch-backend cpu --index-strategy unsafe-best-match +uv pip install -r requirements/cpu.txt --torch-backend cpu --index-strategy unsafe-best-match ``` ??? console "pip" diff --git a/docs/getting_started/installation/cpu.md b/docs/getting_started/installation/cpu.md index 7225d1d6c77b..8b3605e8557d 100644 --- a/docs/getting_started/installation/cpu.md +++ b/docs/getting_started/installation/cpu.md @@ -142,6 +142,10 @@ VLLM_USE_PRECOMPILED=1 VLLM_PRECOMPILED_WHEEL_VARIANT=cpu VLLM_TARGET_DEVICE=cpu === "IBM Z (S390X)" --8<-- "docs/getting_started/installation/cpu.s390x.inc.md:build-image-from-source" +## AMD Zen optimizations {#amd-zen-optimizations} + +--8<-- "docs/getting_started/installation/cpu.x86.inc.md:amd-zen-optimizations" + ## Related runtime environment variables - `VLLM_CPU_KVCACHE_SPACE`: specify the KV Cache size (e.g, `VLLM_CPU_KVCACHE_SPACE=40` means 40 GiB space for KV cache), larger setting will allow vLLM to run more requests in parallel. This parameter should be set based on the hardware configuration and memory management pattern of users. Default value is `0`. @@ -149,12 +153,14 @@ VLLM_USE_PRECOMPILED=1 VLLM_PRECOMPILED_WHEEL_VARIANT=cpu VLLM_TARGET_DEVICE=cpu - `VLLM_CPU_NUM_OF_RESERVED_CPU`: specify the number of CPU cores which are not dedicated to the OpenMP threads for each rank. The variable only takes effect when VLLM_CPU_OMP_THREADS_BIND is set to `auto`. Default value is `None`. If the value is not set and use `auto` thread binding, no CPU will be reserved for `world_size == 1`, 1 CPU per rank will be reserved for `world_size > 1`. - `CPU_VISIBLE_MEMORY_NODES`: specify visible NUMA memory nodes for vLLM CPU workers, similar to ```CUDA_VISIBLE_DEVICES```. The variable only takes effect when VLLM_CPU_OMP_THREADS_BIND is set to `auto`. The variable provides more control for the auto thread-binding feature, such as masking nodes and changing nodes binding sequence. - `VLLM_CPU_SGL_KERNEL` (x86 only, Experimental): whether to use small-batch optimized kernels for linear layer and MoE layer, especially for low-latency requirements like online serving. The kernels require AMX instruction set, BFloat16 weight type and weight shapes divisible by 32. Default is `0` (False). +- `VLLM_ZENTORCH_WEIGHT_PREPACK` (AMD Zen only): when `ZenCpuPlatform` is active, eagerly prepack linear weights into ZenDNN's blocked layout at model load time, eliminating per-inference layout conversion overhead. Default is `1` (enabled). See [AMD Zen optimizations](#amd-zen-optimizations). ## FAQ ### Which `dtype` should be used? - Currently, vLLM CPU uses model default settings as `dtype`. However, due to unstable float16 support in torch CPU, it is recommended to explicitly set `dtype=bfloat16` if there are any performance or accuracy problem. +- On AMD Zen CPUs (`ZenCpuPlatform`), `float16` is **not** supported. Only `bfloat16` and `float32` are accepted; models declared with `float16` are auto-downcast to `bfloat16` at model load time. See [AMD Zen optimizations](#amd-zen-optimizations). ### How to launch a vLLM service on CPU? @@ -227,6 +233,25 @@ By providing MODEL_FILTER and DTYPE_FILTER, only commands for related model ID a ON_CPU=1 SERVING_JSON=serving-tests-cpu-text.json DRY_RUN=1 MODEL_FILTER=meta-llama/Llama-3.1-8B-Instruct DTYPE_FILTER=bfloat16 bash .buildkite/performance-benchmarks/scripts/run-performance-benchmarks.sh ``` +### How do I enable AMD Zen optimizations? {#how-do-i-enable-amd-zen-optimizations} + +On an AMD Zen 4 / Zen 5 CPU, install the CPU wheel with the `zen` extra so vLLM pulls the tested `zentorch` version for that release: + +```bash +export VLLM_VERSION=$(curl -s https://api.github.com/repos/vllm-project/vllm/releases/latest | jq -r .tag_name | sed 's/^v//') +uv pip install "vllm[zen]" --extra-index-url https://wheels.vllm.ai/${VLLM_VERSION}/cpu --index-strategy first-index --torch-backend cpu +``` + +vLLM auto-detects the platform and routes linear layers through ZenDNN-optimized kernels - no flag needed. To verify it is engaged, look for the platform-selection line in the server's startup logs: + +```bash +vllm serve Qwen/Qwen3-0.6B 2>&1 | grep "AMD Zen CPU detected with zentorch installed" +``` + +For per-backend dispatch details (which kernel each linear layer was bound to), re-run with `VLLM_LOGGING_LEVEL=DEBUG` and grep for `CPU unquantized GEMM dispatch`. + +See [AMD Zen optimizations](#amd-zen-optimizations) for detection rules, supported dtypes, and the `VLLM_ZENTORCH_WEIGHT_PREPACK` knob. + ### How to decide `VLLM_CPU_OMP_THREADS_BIND`? - Default `auto` thread-binding is recommended for most cases. Ideally, each OpenMP thread will be bound to a dedicated physical core respectively, threads of each rank will be bound to the same NUMA node respectively, and 1 CPU per rank will be reserved for other vLLM components when `world_size > 1`. If you have any performance problems or unexpected binding behaviours, please try to bind threads as following. diff --git a/docs/getting_started/installation/cpu.x86.inc.md b/docs/getting_started/installation/cpu.x86.inc.md index ad051d22dc8c..32295d63879f 100644 --- a/docs/getting_started/installation/cpu.x86.inc.md +++ b/docs/getting_started/installation/cpu.x86.inc.md @@ -1,4 +1,4 @@ - + --8<-- [start:installation] vLLM supports basic model inferencing and serving on x86 CPU platform, with data types FP32, FP16 and BF16. @@ -88,8 +88,8 @@ cd vllm_source Install the required dependencies: ```bash -uv pip install -r requirements/build/cpu.txt --torch-backend cpu -uv pip install -r requirements/cpu.txt --torch-backend cpu +uv pip install -r requirements/build/cpu.txt --torch-backend cpu --index-strategy unsafe-best-match +uv pip install -r requirements/cpu.txt --torch-backend cpu --index-strategy unsafe-best-match ``` ??? console "pip" @@ -200,7 +200,19 @@ docker build -f docker/Dockerfile.cpu \ --target vllm-openai . ``` -#### Launching the OpenAI server +#### Building with AMD Zen optimizations + +For AMD Zen 4 / Zen 5 hosts (`linux/amd64` only), use the `vllm-openai-zen` target. It extends the default `vllm-openai` image and adds `zentorch` via the `vllm[zen]` extra so `ZenCpuPlatform` auto-activates at runtime: + +```bash +docker build -f docker/Dockerfile.cpu \ + --tag vllm-cpu-zen-env \ + --target vllm-openai-zen . +``` + +The resulting image accepts the same arguments and environment variables as `vllm-openai` (see [Launching the OpenAI server](#launching-the-openai-server) below); no extra flag is needed to engage Zen optimizations. See [AMD Zen optimizations](cpu.md#amd-zen-optimizations) for runtime behavior and the supported-dtype caveats. + +#### Launching the OpenAI server {#launching-the-openai-server} ```bash docker run --rm \ @@ -216,5 +228,36 @@ docker run --rm \ ``` --8<-- [end:build-image-from-source] +--8<-- [start:amd-zen-optimizations] + +On AMD Zen CPUs, vLLM auto-selects `ZenCpuPlatform` (a subclass of `CpuPlatform`) which dispatches linear layers through [`zentorch`](https://github.com/amd/ZenDNN-pytorch-plugin)'s ZenDNN-optimized kernels. See the FAQ entry [How do I enable AMD Zen optimizations?](#how-do-i-enable-amd-zen-optimizations) for the install command. + +### Detection rules + +`ZenCpuPlatform` is selected when **all** of the following hold: + +- vLLM is built for CPU +- `/proc/cpuinfo` reports `AuthenticAMD` and `avx512` +- `import zentorch` succeeds + +Otherwise, vLLM falls back to the default `CpuPlatform` (oneDNN / sgl-kernel paths). + +### Supported dtypes + +`float16` is **not** supported on `ZenCpuPlatform`. `ZenCpuPlatform.supported_dtypes` advertises only `bfloat16` and `float32`, so models declared with `torch_dtype=float16` are auto-downcast to `bfloat16` at load time with the standard `"Your device 'cpu' doesn't support torch.float16. Falling back to torch.bfloat16 for compatibility."` warning emitted from `vllm/config/model.py`. + +### Environment variables + +- `VLLM_ZENTORCH_WEIGHT_PREPACK` (default `1`): eagerly prepacks linear weights into ZenDNN's blocked layout at model load time, eliminating per-inference layout conversion overhead. Set to `0` to disable. + +### Docker + +The `vllm-openai-zen` Docker target (in `docker/Dockerfile.cpu`) extends the default `vllm-openai` image with `vllm[zen]`. Build it with `docker build -f docker/Dockerfile.cpu --target vllm-openai-zen .` — see [Building with AMD Zen optimizations](#building-with-amd-zen-optimizations) for the full command and run instructions. + +### Reference + +For the design rationale, see [RFC #35089: In-Tree AMD Zen CPU Backend via zentorch](https://github.com/vllm-project/vllm/issues/35089). + +--8<-- [end:amd-zen-optimizations] --8<-- [start:extra-information] --8<-- [end:extra-information] diff --git a/docs/getting_started/installation/gpu.rocm.inc.md b/docs/getting_started/installation/gpu.rocm.inc.md index f8385997eea3..59c9723e666b 100644 --- a/docs/getting_started/installation/gpu.rocm.inc.md +++ b/docs/getting_started/installation/gpu.rocm.inc.md @@ -27,6 +27,19 @@ If you need a different ROCm version or want to use an existing PyTorch installa --8<-- [end:set-up-using-python] --8<-- [start:pre-built-wheels] +!!! warning "Python 3.12 required for ROCm wheels" + + ROCm pre-built wheels are only available for **Python 3.12**. If you are using a different Python version (e.g. 3.11 or 3.13), the installer **will silently fall back** to the CUDA wheel from PyPI, which will fail on AMD GPUs with errors like `libcudart.so: cannot open shared object file`. + + To check your Python version: `python3 --version` + + If you need Python 3.12, you can create an isolated environment with `uv`: + + ```bash + uv venv --python 3.12 --seed --managed-python + source .venv/bin/activate + ``` + To install the latest version of vLLM for Python 3.12, ROCm 7.0 and `glibc >= 2.35`. ```bash diff --git a/docs/mkdocs/hooks/generate_examples.py b/docs/mkdocs/hooks/generate_examples.py index 194db05e395e..07fbd7e4d555 100644 --- a/docs/mkdocs/hooks/generate_examples.py +++ b/docs/mkdocs/hooks/generate_examples.py @@ -32,7 +32,6 @@ def title(text: str) -> str: "mae": "MAE", "ner": "NER", "tpu": "TPU", - "gguf": "GGUF", "lora": "LoRA", "nccl": "NCCL", "rlhf": "RLHF", diff --git a/docs/models/hardware_supported_models/cpu.md b/docs/models/hardware_supported_models/cpu.md index 9c6dd9feb793..ddc519e8f16e 100644 --- a/docs/models/hardware_supported_models/cpu.md +++ b/docs/models/hardware_supported_models/cpu.md @@ -1,5 +1,8 @@ # CPU - Intel® Xeon® +!!! note "AMD Zen CPUs" + On AMD Zen 4 / Zen 5 CPUs, AMD Zen optimizations are auto-enabled when the [`zentorch`](https://github.com/amd/ZenDNN-pytorch-plugin) package is installed. All models supported by vLLM on CPU are supported on AMD Zen as well; model compatibility does not change. This page reflects the current CPU reference validation matrix on Intel systems. See [AMD Zen optimizations](../../getting_started/installation/cpu.md#amd-zen-optimizations) for details. + ## Validated Hardware | Hardware | diff --git a/docs/models/pooling_models/README.md b/docs/models/pooling_models/README.md index 2a5357e4fee6..d9ce27dd216d 100644 --- a/docs/models/pooling_models/README.md +++ b/docs/models/pooling_models/README.md @@ -184,7 +184,7 @@ Our online Server provides endpoints that correspond to the offline APIs: - Corresponding to `LLM.classify`: - [Classification API](classify.md#online-serving)(`/classify`) - Corresponding to `LLM.score`: - - [Score API](scoring.md#score-api)(`/score`) + - [Score API](scoring.md#score-api) (`/score`, `/v1/score`) - [Cohere Rerank API](scoring.md#rerank-api) (`/rerank`, `/v1/rerank`, `/v2/rerank`) - Pooling API (`/pooling`) is similar to `LLM.encode`, being applicable to all types of pooling models. diff --git a/docs/models/pooling_models/scoring.md b/docs/models/pooling_models/scoring.md index c8b4c73cfb30..a4b0fe5d2ea8 100644 --- a/docs/models/pooling_models/scoring.md +++ b/docs/models/pooling_models/scoring.md @@ -19,7 +19,7 @@ The score models is designed to compute similarity scores between two input prom - Offline APIs: - `LLM.score` - Online APIs: - - [Score API](scoring.md#score-api) (`/score`) + - [Score API](scoring.md#score-api) (`/score`, `/v1/score`) - [Cohere Rerank API](scoring.md#rerank-api) (`/rerank`, `/v1/rerank`, `/v2/rerank`) !!! note @@ -157,7 +157,7 @@ A code example can be found here: [examples/basic/offline_inference/score.py](.. ### Score API -Our Score API (`/score`) is similar to `LLM.score`, compute similarity scores between two input prompts. +Our Score API (`/score`, `/v1/score`) is similar to `LLM.score`, compute similarity scores between two input prompts. #### Parameters diff --git a/docs/models/supported_models.md b/docs/models/supported_models.md index 1823ddcecc60..0826ec7d572d 100644 --- a/docs/models/supported_models.md +++ b/docs/models/supported_models.md @@ -386,7 +386,6 @@ th { | `DeepseekV2ForCausalLM` | DeepSeek-V2 | `deepseek-ai/DeepSeek-V2`, `deepseek-ai/DeepSeek-V2-Chat`, etc. | ✅︎ | ✅︎ | | `DeepseekV3ForCausalLM` | DeepSeek-V3 | `deepseek-ai/DeepSeek-V3`, `deepseek-ai/DeepSeek-R1`, `deepseek-ai/DeepSeek-V3.1`, etc. | ✅︎ | ✅︎ | | `DeepseekV4ForCausalLM` | DeepSeek-V4 | `deepseek-ai/DeepSeek-V4-Flash`, `deepseek-ai/DeepSeek-V4-Pro`, etc. | | ✅︎ | -| `Dots1ForCausalLM` | dots.llm1 | `rednote-hilab/dots.llm1.base`, `rednote-hilab/dots.llm1.inst`, etc. | | ✅︎ | | `DotsOCRForCausalLM` | dots_ocr | `rednote-hilab/dots.ocr` | ✅︎ | ✅︎ | | `Ernie4_5ForCausalLM` | Ernie4.5 | `baidu/ERNIE-4.5-0.3B-PT`, etc. | ✅︎ | ✅︎ | | `Ernie4_5_MoeForCausalLM` | Ernie4.5MoE | `baidu/ERNIE-4.5-21B-A3B-PT`, `baidu/ERNIE-4.5-300B-A47B-PT`, etc. | ✅︎ | ✅︎ | @@ -419,6 +418,7 @@ th { | `GritLM` | GritLM | `parasail-ai/GritLM-7B-vllm`. | ✅︎ | ✅︎ | | `Grok1ModelForCausalLM` | Grok1 | `hpcai-tech/grok-1`. | ✅︎ | ✅︎ | | `Grok1ForCausalLM` | Grok2 | `xai-org/grok-2` | ✅︎ | ✅︎ | +| `HrmTextForCausalLM` | HRM-Text | `sapientinc/HRM-Text-1B`, etc. | | | | `HunYuanDenseV1ForCausalLM` | Hunyuan Dense | `tencent/Hunyuan-7B-Instruct` | ✅︎ | ✅︎ | | `HunYuanMoEV1ForCausalLM` | Hunyuan-A13B | `tencent/Hunyuan-A13B-Instruct`, `tencent/Hunyuan-A13B-Pretrain`, `tencent/Hunyuan-A13B-Instruct-FP8`, etc. | ✅︎ | ✅︎ | | `HYV3ForCausalLM` | HY3 | `tencent/Hy3-preview-Base`, `tencent/Hy3-preview` | ✅︎ | ✅︎ | @@ -488,7 +488,6 @@ th { | `TeleChat2ForCausalLM` | TeleChat2 | `Tele-AI/TeleChat2-3B`, `Tele-AI/TeleChat2-7B`, `Tele-AI/TeleChat2-35B`, etc. | ✅︎ | ✅︎ | | `TeleChat3ForCausalLM` | TeleChat3 | `Tele-AI/TeleChat3-36B-Thinking`, `Tele-AI/TeleChat3-Coder-36B-Thinking`, etc. | ✅︎ | ✅︎ | | `TeleFLMForCausalLM` | TeleFLM | `CofeAI/FLM-2-52B-Instruct-2407`, `CofeAI/Tele-FLM`, etc. | ✅︎ | ✅︎ | -| `XverseForCausalLM` | XVERSE | `xverse/XVERSE-7B-Chat`, `xverse/XVERSE-13B-Chat`, `xverse/XVERSE-65B-Chat`, etc. | ✅︎ | ✅︎ | | `MiniMaxM1ForCausalLM` | MiniMax-Text | `MiniMaxAI/MiniMax-M1-40k`, `MiniMaxAI/MiniMax-M1-80k`, etc. | | | | `MiniMaxText01ForCausalLM` | MiniMax-Text | `MiniMaxAI/MiniMax-Text-01`, etc. | | | | `Zamba2ForCausalLM` | Zamba2 | `Zyphra/Zamba2-7B-instruct`, `Zyphra/Zamba2-2.7B-instruct`, `Zyphra/Zamba2-1.2B-instruct`, etc. | | | @@ -577,7 +576,7 @@ These models primarily accept the [`LLM.generate`](./generative_models.md#llmgen | `InternS1ForConditionalGeneration` | Intern-S1 | T + IE+ + VE+ | `internlm/Intern-S1`, `internlm/Intern-S1-mini`, etc. | ✅︎ | ✅︎ | | `InternS1ProForConditionalGeneration` | Intern-S1-Pro | T + IE+ + VE+ | `internlm/Intern-S1-Pro`, etc. | ✅︎ | ✅︎ | | `InternS2PreviewForConditionalGeneration` | Intern-S2-Preview | T + IE+ + VE+ | `internlm/Intern-S2-Preview`, etc. | ✅︎ | ✅︎ | -| `InternVLChatModel` | InternVL 3.5, InternVL 3.0, InternVideo 2.5, InternVL 2.5, Mono-InternVL, InternVL 2.0 | T + IE+ + (VE+) | `OpenGVLab/InternVL3_5-14B`, `OpenGVLab/InternVL3-9B`, `OpenGVLab/InternVideo2_5_Chat_8B`, `OpenGVLab/InternVL2_5-4B`, `OpenGVLab/Mono-InternVL-2B`, `OpenGVLab/InternVL2-4B`, etc. | ✅︎ | ✅︎ | +| `InternVLChatModel` | InternVL 3.5, InternVL 3.0, InternVideo 2.5, InternVL 2.5, InternVL 2.0 | T + IE+ + (VE+) | `OpenGVLab/InternVL3_5-14B`, `OpenGVLab/InternVL3-9B`, `OpenGVLab/InternVideo2_5_Chat_8B`, `OpenGVLab/InternVL2_5-4B`, `OpenGVLab/InternVL2-4B`, etc. | ✅︎ | ✅︎ | | `InternVLForConditionalGeneration` | InternVL 3.0 (HF format) | T + IE+ + VE+ | `OpenGVLab/InternVL3-1B-hf`, etc. | ✅︎ | ✅︎ | | `KananaVForConditionalGeneration` | Kanana-V | T + I+ | `kakaocorp/kanana-1.5-v-3b-instruct`, etc. | | ✅︎ | | `KeyeForConditionalGeneration` | Keye-VL-8B-Preview | T + IE+ + VE+ | `Kwai-Keye/Keye-VL-8B-Preview` | ✅︎ | ✅︎ | diff --git a/docs/serving/online_serving/README.md b/docs/serving/online_serving/README.md index 9fa1763108cb..40fc8b7c4266 100644 --- a/docs/serving/online_serving/README.md +++ b/docs/serving/online_serving/README.md @@ -9,12 +9,13 @@ We currently support the following OpenAI APIs: - [Completions API](./openai_compatible_server.md#completions-api) (`/v1/completions`) - Only applicable to [text generation models](../../models/generative_models.md). - *Note: `suffix` parameter is not supported.* -- [Responses API](./openai_compatible_server.md#responses-api) (`/v1/responses`) - - Only applicable to [text generation models](../../models/generative_models.md). - [Chat Completions API](./openai_compatible_server.md#chat-api) (`/v1/chat/completions`) - Only applicable to [text generation models](../../models/generative_models.md) with a [chat template](./openai_compatible_server.md#chat-template). - *Note: `user` parameter is ignored.* - *Note:* Setting the `parallel_tool_calls` parameter to `false` ensures vLLM only returns zero or one tool call per request. Setting it to `true` (the default) allows returning more than one tool call per request. There is no guarantee more than one tool call will be returned if this is set to `true`, as that behavior is model dependent and not all models are designed to support parallel tool calls. +- [Chat Completions batch API](./openai_compatible_server.md#chat-api) (`/v1/chat/completions/batch`) +- [Responses API](./openai_compatible_server.md#responses-api) (`/v1/responses`, `/v1/responses/{response_id}`, `/v1/responses/{response_id}/cancel`) + - Only applicable to [text generation models](../../models/generative_models.md). - [Embeddings API](../../models/pooling_models/embed.md#openai-compatible-embeddings-api) (`/v1/embeddings`) - Only applicable to [embedding models](../../models/pooling_models/embed.md). - [Transcriptions API](./speech_to_text.md#transcriptions-api) (`/v1/audio/transcriptions`) @@ -24,7 +25,7 @@ We currently support the following OpenAI APIs: ## Anthropic APIs -- Anthropic messages API (`/v1/messages`) +- Anthropic messages API (`/v1/messages`, `/v1/messages/count_tokens`) ## Cohere APIs @@ -35,10 +36,6 @@ We currently support the following OpenAI APIs: - Implements [Jina AI's v1 rerank API](https://jina.ai/reranker/) - compatible with [Cohere's v1 & v2 rerank APIs](https://docs.cohere.com/v2/reference/rerank) -## SageMaker APIs - -- `/invocations` - SageMaker-compatible endpoint (routes to the same inference functions as `/v1` endpoints) - ## Pooling APIs For further details on pooling models, please refer to [this page](../../models/pooling_models/README.md). @@ -51,7 +48,7 @@ For further details on pooling models, please refer to [this page](../../models/ - [OpenAI-compatible Embeddings API](../../models/pooling_models/embed.md#openai-compatible-embeddings-api) (`/v1/embeddings`) - Only applicable to [embedding models](../../models/pooling_models/embed.md). - [Scoring Usages](../../models/pooling_models/scoring.md) - - [Score API](../../models/pooling_models/scoring.md#score-api) (`/score`) + - [Score API](../../models/pooling_models/scoring.md#score-api) (`/score`, `/v1/score`) - [Cohere Rerank API](../../models/pooling_models/scoring.md#rerank-api) (`/rerank`, `/v1/rerank`, `/v2/rerank`) - Applicable to [score models](../../models/pooling_models/scoring.md) (cross-encoder, bi-encoder, late-interaction). - [Pooling API](../../models/pooling_models/README.md#pooling-api) (`/pooling`) @@ -68,17 +65,6 @@ For further details on speech to text, please refer to [this page](speech_to_tex - [Realtime API](./speech_to_text.md#realtime-api) (`/v1/realtime`) - Only applicable to [Automatic Speech Recognition (ASR) models](../../models/supported_models.md#realtime-transcription). -## Disaggregated APIs - -### Renderer APIs - -For further details on renderer APIs, please refer to [this page](renderer.md). - -- [Completions Render API](renderer.md) (`/v1/completions/render`) - - Render completion requests -- [Chat Completions Render API](renderer.md) (`/v1/chat/completions/render`) - - Render chat completions - ## Custom APIs - [Classification API](../../models/pooling_models/classify.md#classification-api) (`/classify`) @@ -91,14 +77,79 @@ For further details on renderer APIs, please refer to [this page](renderer.md). - Applicable to [CausalLM models](../../models/generative_models.md) (task `"generate"`). - Computes next-token probabilities for specified `label_token_ids`. -## Utility APIs +## Instrumentator APIs + +### Basic APIs -- `/tokenize` - Tokenize text -- `/detokenize` - Detokenize tokens -- `/health` - Health check -- `/ping` - SageMaker health check - `/version` - Version information - `/load` - Server load metrics +- `/v1/models` - List available models +- `/health` - Health check + +### Metrics APIs + +For further details on metrics, please refer to [this page](../../design/metrics.md). + +- `/metrics` - Prometheus-compatible metrics HTTP endpoint + +### Offline API Documentation + +The FastAPI `/docs` endpoint requires an internet connection by default. To enable offline access in air-gapped environments, use the `--enable-offline-docs` flag: + +```bash +vllm serve NousResearch/Meta-Llama-3-8B-Instruct --enable-offline-docs +``` + +### LoRA dynamic loading + +LoRA dynamic loading & unloading is enabled in the API server. This should ONLY be used for local development! + +- `/v1/load_lora_adapter` - LoRA dynamic loading +- `/v1/unload_lora_adapter` - LoRA dynamic unloading + +### Profiling APIs + +For further details on profiling vLLM, please refer to [this page](../../contributing/profiling.md). + +- `/start_profile` - Start PyTorch profiler +- `/stop_profile` - Stop PyTorch profiler + +### SageMaker APIs + +- `/ping` - SageMaker health check +- `/invocations` - SageMaker-compatible endpoint (routes to the same inference functions as `/v1` endpoints) + +## Disaggregated Everything + +### Tokens IN <> Tokens OUT + +- `/inference/v1/generate` - Generate completions +- `/abort_requests` - Abort in-flight requests (only when `--tokens-only` is also set) + +### Renderer APIs + +For further details on renderer APIs, please refer to [this page](renderer.md). + +- [Completions Render API](renderer.md) (`/v1/completions/render`) + - Render completion requests +- [Chat Completions Render API](renderer.md) (`/v1/chat/completions/render`) + - Render chat completions + +### Derenderer APIs + +- `/v1/completions/derender` - Derenderer completion requests +- `/v1/chat/completions/derender` - Derenderer chat completion requests + +## Tokenize APIs + +- `/tokenize` - Tokenize text +- `/detokenize` - Detokenize tokens +- `/tokenizer_info` - Get comprehensive tokenizer information including chat templates and configuration + +## Elastic Expert Parallelism (EEP) + +- `/scale_elastic_ep` - Trigger scaling operations +- `/is_scaling_elastic_ep` - Check if scaling is in progress ## Server in development mode @@ -120,7 +171,9 @@ For further details on Weight Transfer, please refer to [this page](../../traini - `/resume` - Resume generation - `/is_paused` - Check if generation is paused - `/init_weight_transfer_engine` - Initialize weight transfer engine for RLHF +- `/start_weight_update` - Prepares the inference engine for a weight update. - `/update_weights` - Update model weights (can alter model behavior) +- `/finish_weight_update` - Finalizes the weight update - `/get_world_size` - Get distributed world size ### Collective RPC @@ -189,14 +242,6 @@ the detected format, which can be one of: If the result is not what you expect, you can set the `--chat-template-content-format` CLI argument to override which format to use. -## Offline API Documentation - -The FastAPI `/docs` endpoint requires an internet connection by default. To enable offline access in air-gapped environments, use the `--enable-offline-docs` flag: - -```bash -vllm serve NousResearch/Meta-Llama-3-8B-Instruct --enable-offline-docs -``` - ## Ray Serve LLM Ray Serve LLM enables scalable, production-grade serving of the vLLM engine. It integrates tightly with vLLM and extends it with features such as auto-scaling, load balancing, and back-pressure. diff --git a/docs/serving/online_serving/openai_compatible_server.md b/docs/serving/online_serving/openai_compatible_server.md index 245de012bff1..e50754aa9c01 100644 --- a/docs/serving/online_serving/openai_compatible_server.md +++ b/docs/serving/online_serving/openai_compatible_server.md @@ -9,12 +9,13 @@ We currently support the following OpenAI APIs: - [Completions API](#completions-api) (`/v1/completions`) - Only applicable to [text generation models](../../models/generative_models.md). - *Note: `suffix` parameter is not supported.* -- [Responses API](#responses-api) (`/v1/responses`) - - Only applicable to [text generation models](../../models/generative_models.md). - [Chat Completions API](#chat-api) (`/v1/chat/completions`) - Only applicable to [text generation models](../../models/generative_models.md) with a [chat template](../online_serving/README.md#chat-template). - *Note: `user` parameter is ignored.* - *Note:* Setting the `parallel_tool_calls` parameter to `false` ensures vLLM only returns zero or one tool call per request. Setting it to `true` (the default) allows returning more than one tool call per request. There is no guarantee more than one tool call will be returned if this is set to `true`, as that behavior is model dependent and not all models are designed to support parallel tool calls. +- [Chat Completions batch API](#chat-api) (`/v1/chat/completions/batch`) +- [Responses API](#responses-api) (`/v1/responses`, `/v1/responses/{response_id}`, `/v1/responses/{response_id}/cancel`) + - Only applicable to [text generation models](../../models/generative_models.md). - [Embeddings API](../../models/pooling_models/embed.md#openai-compatible-embeddings-api) (`/v1/embeddings`) - Only applicable to [embedding models](../../models/pooling_models/embed.md). - [Transcriptions API](./speech_to_text.md#transcriptions-api) (`/v1/audio/transcriptions`) diff --git a/docs/training/layerwise.md b/docs/training/layerwise.md index d304c4a8425d..9e7d187710dd 100644 --- a/docs/training/layerwise.md +++ b/docs/training/layerwise.md @@ -28,9 +28,9 @@ For more information on implementation, see [Low Level `layerwise` API](#low-lev Online quantization refers to when a user provides full precision weights and those weights are quantized on-the-fly as they are loaded into the model. The layerwise reloading system handles this by treating online quantization as a **processing** step, which is then handled in an online way both during first-time load and during reload. A typical online quantization method implementation should look like this: ```python -class Fp8OnlineLinearMethod(Fp8LinearMethod): - """Online version of Fp8LinearMethod which loads a full precision checkpoint - and quantizes weights during loading.""" +class Fp8PerTensorOnlineLinearMethod(LinearMethodBase): + """Online version of FP8 per-tensor quantization which loads a full + precision checkpoint and quantizes weights during loading.""" uses_meta_device: bool = True diff --git a/examples/chat_template_qwen35_fixed.jinja b/examples/chat_template_qwen35_fixed.jinja new file mode 100644 index 000000000000..166818aa3ffa --- /dev/null +++ b/examples/chat_template_qwen35_fixed.jinja @@ -0,0 +1,277 @@ +{#- Qwen3.5 Fixed Chat Template -#} +{#- -#} +{#- Config (--chat-template-kwargs): -#} +{#- enable_thinking / thinking bool (default true) -#} +{#- auto_disable_thinking_with_tools bool (default true) -#} +{#- preserve_thinking bool (default false) -#} +{#- add_vision_id bool (default false) -#} +{#- max_tool_arg_chars int (default 0 = unlimited) -#} +{#- max_tool_response_chars int (default 0 = unlimited) -#} +{#- max_context_turns int (default 0 = unlimited) -#} +{#- ======================================================================== -#} + +{%- if enable_thinking is not defined -%} + {%- set enable_thinking = thinking if thinking is defined else true -%} +{%- endif -%} +{%- set auto_disable_thinking_with_tools = auto_disable_thinking_with_tools if auto_disable_thinking_with_tools is defined else false -%} +{%- set preserve_thinking = preserve_thinking if preserve_thinking is defined else false -%} +{%- set add_vision_id = add_vision_id if add_vision_id is defined else false -%} +{%- set max_tool_arg_chars = max_tool_arg_chars if max_tool_arg_chars is defined else 0 -%} +{%- set max_tool_response_chars = max_tool_response_chars if max_tool_response_chars is defined else 0 -%} +{%- set max_context_turns = max_context_turns if max_context_turns is defined else 0 -%} + +{%- set _has_tools = (tools is defined and tools and tools is iterable and tools is not mapping) -%} +{%- set _thinking = enable_thinking and not (auto_disable_thinking_with_tools and _has_tools) -%} + +{%- set image_count = namespace(value=0) -%} +{%- set video_count = namespace(value=0) -%} + +{#- ── render_content ──────────────────────────────────────────────────────── -#} +{%- macro render_content(content, count_vision=false, is_system=false) -%} + {%- if content is string -%} + {{- content -}} + {%- elif content is iterable and content is not mapping -%} + {%- for item in content -%} + {%- if item is mapping -%} + {%- if item.type == 'image' or item.image is defined or item.image_url is defined -%} + {%- if is_system -%}{{- raise_exception('System message cannot contain images.') -}}{%- endif -%} + {%- if count_vision -%}{%- set image_count.value = image_count.value + 1 -%}{%- endif -%} + {%- if add_vision_id -%}{{- 'Picture ' ~ image_count.value ~ ': ' -}}{%- endif -%} + {{- '<|vision_start|><|image_pad|><|vision_end|>' -}} + {%- elif item.type == 'video' or item.video is defined -%} + {%- if is_system -%}{{- raise_exception('System message cannot contain videos.') -}}{%- endif -%} + {%- if count_vision -%}{%- set video_count.value = video_count.value + 1 -%}{%- endif -%} + {%- if add_vision_id -%}{{- 'Video ' ~ video_count.value ~ ': ' -}}{%- endif -%} + {{- '<|vision_start|><|video_pad|><|vision_end|>' -}} + {%- elif item.text is defined -%} + {{- item.text -}} + {%- else -%} + {{- raise_exception('Unexpected item type in content: ' ~ (item | string)[:80]) -}} + {%- endif -%} + {%- else -%} + {{- item | string -}} + {%- endif -%} + {%- endfor -%} + {%- elif content is none or content is undefined -%} + {{- '' -}} + {%- else -%} + {{- raise_exception('Unexpected content type: expected string, list, or null.') -}} + {%- endif -%} +{%- endmacro -%} + +{#- ── render_tool_param: single V with truncation ─ -#} +{%- macro render_tool_param(k, v) -%} + {{- '\n' -}} + {%- if v is mapping or (v is sequence and v is not string) -%} + {%- set _av = v | tojson(ensure_ascii=False) -%} + {%- else -%} + {%- set _av = v | string -%} + {%- endif -%} + {%- if max_tool_arg_chars > 0 and _av | length > max_tool_arg_chars -%} + {{- _av[:max_tool_arg_chars] ~ '\n[TRUNCATED]' -}} + {%- else -%} + {{- _av -}} + {%- endif -%} + {{- '\n\n' -}} +{%- endmacro -%} + +{#- ── Preamble ────────────────────────────────────────────────────────────── -#} +{%- if not messages -%}{{- raise_exception('No messages provided.') -}}{%- endif -%} + +{%- set _sys_msg = none -%} +{%- set _msgs = messages -%} +{%- if messages[0].role == 'system' or messages[0].role == 'developer' -%} + {%- set _sys_msg = messages[0] -%} + {%- set _msgs = messages[1:] -%} +{%- endif -%} + +{#- Validate no mid-conversation system/developer messages -#} +{%- for message in _msgs -%} + {%- if message.role == 'system' or message.role == 'developer' -%} + {{- raise_exception('System/developer message must be at the beginning of the conversation.') -}} + {%- endif -%} +{%- endfor -%} + +{%- set _dropped = 0 -%} +{%- set _compression = false -%} +{%- if max_context_turns > 0 and _msgs | length > max_context_turns -%} + {%- set _dropped = _msgs | length - max_context_turns -%} + {%- set _msgs = _msgs[_dropped:] -%} + {%- set _compression = true -%} +{%- endif -%} + +{#- ── System / Tools block ────────────────────────────────────────────────── -#} +{%- if _has_tools -%} + {{- '<|im_start|>system\n# Tools\n\n' -}} + {%- for tool in tools -%} + {{- '\n' ~ (tool | tojson(ensure_ascii=False)) -}} + {%- endfor -%} + {{- '\n\n\n' -}} + {{- 'To call a function, reply in this exact format:\n' -}} + {{- '\n\n\nvalue\n\n\n\n\n' -}} + {{- 'Rules:\n' -}} + {{- '- Wrap each call in containing \n' -}} + {{- '- All required parameters MUST be included\n' -}} + {{- '- Reasoning BEFORE the call only, never after\n' -}} + {{- '- Multiple calls: separate each block with a blank line\n' -}} + {{- '- No matching function: answer normally, do not mention tools' -}} + {%- if _sys_msg is not none -%} + {%- set _sc = render_content(_sys_msg.content, false, true) | trim -%} + {%- if _sc -%}{{- '\n\n' ~ _sc -}}{%- endif -%} + {%- endif -%} + {{- '<|im_end|>\n' -}} +{%- elif _sys_msg is not none -%} + {{- '<|im_start|>system\n' ~ render_content(_sys_msg.content, false, true) | trim ~ '<|im_end|>\n' -}} +{%- endif -%} + +{%- if _compression -%} + {{- '<|im_start|>user\n[Earlier ' ~ _dropped | string ~ ' messages omitted]\n<|im_end|>\n' -}} +{%- endif -%} + +{#- ── Compute last real-user-query index ──────────────────────────────────── -#} +{%- set _last_idx = _msgs | length - 1 -%} +{%- set ns = namespace(found=false, last_query_index=_last_idx) -%} +{%- for message in _msgs[::-1] -%} + {%- if not ns.found and message.role == 'user' -%} + {%- set _rc = render_content(message.content, false) | trim -%} + {%- if not (_rc.startswith('') and _rc.endswith('')) -%} + {%- set ns.found = true -%} + {%- set ns.last_query_index = (_msgs | length - 1) - loop.index0 -%} + {%- endif -%} + {%- endif -%} +{%- endfor -%} +{%- if not ns.found -%} + {{- raise_exception('No user query found in messages.') -}} +{%- endif -%} + +{#- ── Detect tool-relay tail (for generation prompt) ──────────────────────── -#} +{%- set _last_is_tool_relay = false -%} +{%- if _msgs | length > 0 -%} + {%- if _msgs[-1].role == 'tool' -%} + {%- set _last_is_tool_relay = true -%} + {%- elif _msgs[-1].role == 'user' -%} + {%- set _lrc = render_content(_msgs[-1].content, false) | trim -%} + {%- if _lrc.startswith('') and _lrc.endswith('') -%} + {%- set _last_is_tool_relay = true -%} + {%- endif -%} + {%- endif -%} +{%- endif -%} + +{#- ── Main render loop ────────────────────────────────────────────────────── -#} +{%- set ns2 = namespace(prev_role='') -%} +{%- for message in _msgs -%} + {%- set content = render_content(message.content, true) | trim -%} + + {%- if message.role == 'user' -%} + {{- '<|im_start|>user\n' ~ content ~ '<|im_end|>\n' -}} + + {%- elif message.role == 'assistant' -%} + {#- Extract reasoning_content -#} + {%- set reasoning_content = '' -%} + {%- if message.reasoning_content is defined and message.reasoning_content is not none -%} + {%- if message.reasoning_content is string -%} + {%- set reasoning_content = message.reasoning_content -%} + {%- else -%} + {%- set reasoning_content = message.reasoning_content | string -%} + {%- endif -%} + {%- else -%} + {%- if '' in content -%} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') -%} + {%- set content = content.split('')[-1].lstrip('\n') -%} + {%- endif -%} + {%- endif -%} + {%- set reasoning_content = reasoning_content | trim -%} + + {#- Render turn -#} + {#- preserve_thinking=true: always include blocks (even empty) -#} + {#- preserve_thinking=false: only include after last query, skip empty -#} + {#- (keeps prefix-cache hits stable — HF Qwen3.5-122B-A10B disc#22) -#} + {%- if preserve_thinking or (loop.index0 > ns.last_query_index and reasoning_content) -%} + {{- '<|im_start|>assistant\n\n' ~ reasoning_content ~ '\n\n\n' ~ content -}} + {%- else -%} + {{- '<|im_start|>assistant\n' ~ content -}} + {%- endif -%} + + {#- Render tool_calls -#} + {%- if message.tool_calls is defined and message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping -%} + {%- for tool_call in message.tool_calls -%} + {%- set tc = tool_call.function if (tool_call.function is defined and tool_call.function is not none) else tool_call -%} + + {%- if loop.first and content | trim -%} + {{- '\n\n' -}} + {%- elif not loop.first -%} + {{- '\n\n' -}} + {%- endif -%} + + {{- '\n\n' -}} + + {%- if tc.arguments is defined and tc.arguments is not none -%} + {%- if tc.arguments is mapping -%} + {%- for k, v in tc.arguments.items() -%} + {{- render_tool_param(k, v) -}} + {%- endfor -%} + {%- elif tc.arguments is string and tc.arguments | trim -%} + {%- set _trimmed = tc.arguments | trim -%} + {%- if _trimmed.startswith('{') -%} + {%- set _parsed = _trimmed | from_json -%} + {%- if _parsed is mapping -%} + {%- for k, v in _parsed.items() -%} + {{- render_tool_param(k, v) -}} + {%- endfor -%} + {%- else -%} + {{- _trimmed -}} + {%- endif -%} + {%- else -%} + {{- _trimmed -}} + {%- endif -%} + {%- endif -%} + {%- endif -%} + {{- '\n' -}} + {%- endfor -%} + {%- endif -%} + {{- '<|im_end|>\n' -}} + + {%- elif message.role == 'tool' -%} + {%- if ns2.prev_role != 'tool' -%} + {{- '<|im_start|>user' -}} + {%- endif -%} + {%- if max_tool_response_chars > 0 and content | length > max_tool_response_chars -%} + {%- set content = content[:max_tool_response_chars] ~ '\n[TRUNCATED]' -%} + {%- endif -%} + {%- set _rid = '' -%} + {%- if message.tool_call_id is defined and message.tool_call_id is not none -%} + {%- set _rid = message.tool_call_id | string -%} + {%- endif -%} + {%- set _err = (message.is_error is defined and message.is_error) -%} + {%- if _rid and _err -%} + {{- '\n\n' ~ content ~ '\n' -}} + {%- elif _rid -%} + {{- '\n\n' ~ content ~ '\n' -}} + {%- elif _err -%} + {{- '\n\n' ~ content ~ '\n' -}} + {%- else -%} + {{- '\n\n' ~ content ~ '\n' -}} + {%- endif -%} + {%- if loop.last or _msgs[loop.index0 + 1].role != 'tool' -%} + {{- '<|im_end|>\n' -}} + {%- endif -%} + + {%- elif message.role == 'developer' -%} + {#- already rendered above as system -#} + + {%- else -%} + {{- raise_exception('Unexpected message role: ' ~ message.role) -}} + {%- endif -%} + + {%- set ns2.prev_role = message.role -%} +{%- endfor -%} + +{#- ── Generation prompt ───────────────────────────────────────────────────── -#} +{%- if add_generation_prompt -%} + {{- '<|im_start|>assistant\n' -}} + {%- if not _thinking or _last_is_tool_relay -%} + {{- '\n\n\n\n' -}} + {%- else -%} + {{- '\n' -}} + {%- endif -%} +{%- endif -%} diff --git a/examples/chat_template_qwen36_fixed.jinja b/examples/chat_template_qwen36_fixed.jinja new file mode 100644 index 000000000000..f714f3acc59b --- /dev/null +++ b/examples/chat_template_qwen36_fixed.jinja @@ -0,0 +1,291 @@ +{#- Qwen3.6 Fixed Chat Template (based on qwen35-fixed-template) -#} +{#- -#} +{#- Config (--chat-template-kwargs): -#} +{#- enable_thinking / thinking bool (default true) -#} +{#- auto_disable_thinking_with_tools bool (default false) -#} +{#- preserve_thinking bool (default false) -#} +{#- add_vision_id bool (default false) -#} +{#- max_tool_arg_chars int (default 0 = unlimited) -#} +{#- max_tool_response_chars int (default 0 = unlimited) -#} +{#- max_context_turns int (default 0 = unlimited) -#} +{#- ======================================================================== -#} + +{%- if enable_thinking is not defined -%} + {%- set enable_thinking = thinking if thinking is defined else true -%} +{%- endif -%} +{%- set auto_disable_thinking_with_tools = auto_disable_thinking_with_tools if auto_disable_thinking_with_tools is defined else false -%} +{%- set preserve_thinking = preserve_thinking if preserve_thinking is defined else false -%} +{%- set add_vision_id = add_vision_id if add_vision_id is defined else false -%} +{%- set max_tool_arg_chars = max_tool_arg_chars if max_tool_arg_chars is defined else 0 -%} +{%- set max_tool_response_chars = max_tool_response_chars if max_tool_response_chars is defined else 0 -%} +{%- set max_context_turns = max_context_turns if max_context_turns is defined else 0 -%} + +{%- set _has_tools = (tools is defined and tools and tools is iterable and tools is not mapping) -%} +{%- set _thinking = enable_thinking and not (auto_disable_thinking_with_tools and _has_tools) -%} + +{%- set image_count = namespace(value=0) -%} +{%- set video_count = namespace(value=0) -%} + +{#- ── render_content ──────────────────────────────────────────────────────── -#} +{%- macro render_content(content, count_vision=false, is_system=false) -%} + {%- if content is string -%} + {{- content -}} + {%- elif content is iterable and content is not mapping -%} + {%- for item in content -%} + {%- if item is mapping -%} + {%- if item.type == 'image' or item.image is defined or item.image_url is defined -%} + {%- if is_system -%}{{- raise_exception('System message cannot contain images.') -}}{%- endif -%} + {%- if count_vision -%}{%- set image_count.value = image_count.value + 1 -%}{%- endif -%} + {%- if add_vision_id -%}{{- 'Picture ' ~ image_count.value ~ ': ' -}}{%- endif -%} + {{- '<|vision_start|><|image_pad|><|vision_end|>' -}} + {%- elif item.type == 'video' or item.video is defined -%} + {%- if is_system -%}{{- raise_exception('System message cannot contain videos.') -}}{%- endif -%} + {%- if count_vision -%}{%- set video_count.value = video_count.value + 1 -%}{%- endif -%} + {%- if add_vision_id -%}{{- 'Video ' ~ video_count.value ~ ': ' -}}{%- endif -%} + {{- '<|vision_start|><|video_pad|><|vision_end|>' -}} + {%- elif item.text is defined -%} + {{- item.text -}} + {%- else -%} + {{- raise_exception('Unexpected item type in content: ' ~ (item | string)[:80]) -}} + {%- endif -%} + {%- else -%} + {{- item | string -}} + {%- endif -%} + {%- endfor -%} + {%- elif content is none or content is undefined -%} + {{- '' -}} + {%- else -%} + {{- raise_exception('Unexpected content type: expected string, list, or null.') -}} + {%- endif -%} +{%- endmacro -%} + +{#- ── render_tool_param: single V with truncation ─ -#} +{%- macro render_tool_param(k, v) -%} + {{- '\n' -}} + {%- if v is mapping or (v is sequence and v is not string) -%} + {%- set _av = v | tojson(ensure_ascii=False) -%} + {%- else -%} + {%- set _av = v | string -%} + {%- endif -%} + {%- if max_tool_arg_chars > 0 and _av | length > max_tool_arg_chars -%} + {{- _av[:max_tool_arg_chars] ~ '\n[TRUNCATED original_chars=' ~ (_av | length) ~ ' shown_chars=' ~ max_tool_arg_chars ~ ']' -}} + {%- else -%} + {{- _av -}} + {%- endif -%} + {{- '\n\n' -}} +{%- endmacro -%} + +{#- ── Preamble ────────────────────────────────────────────────────────────── -#} +{%- if not messages -%}{{- raise_exception('No messages provided.') -}}{%- endif -%} + +{%- set _sys_msg = none -%} +{%- set _msgs = messages -%} +{%- if messages[0].role == 'system' or messages[0].role == 'developer' -%} + {%- set _sys_msg = messages[0] -%} + {%- set _msgs = messages[1:] -%} +{%- endif -%} + +{%- set _dropped = 0 -%} +{%- set _compression = false -%} +{%- if max_context_turns > 0 and _msgs | length > max_context_turns -%} + {%- set _dropped = _msgs | length - max_context_turns -%} + {%- set _msgs = _msgs[_dropped:] -%} + {%- set _compression = true -%} +{%- endif -%} + +{#- ── System / Tools block ────────────────────────────────────────────────── -#} +{%- if _has_tools -%} + {{- '<|im_start|>system\n# Tools\n\n' -}} + {%- for tool in tools -%} + {{- '\n' ~ (tool | tojson(ensure_ascii=False)) -}} + {%- endfor -%} + {{- '\n\n\n' -}} + {{- 'To call a function, reply in this exact format:\n' -}} + {{- '\n\n\nvalue\n\n\n\n\n' -}} + {{- 'Rules:\n' -}} + {{- '- Wrap each call in containing \n' -}} + {{- '- All required parameters MUST be included\n' -}} + {{- '- Reasoning BEFORE the call only, never after\n' -}} + {{- '- Multiple calls: separate each block with a blank line\n' -}} + {{- '- No matching function: answer normally, do not mention tools' -}} + {%- if _sys_msg is not none -%} + {%- set _sc = render_content(_sys_msg.content, false, true) | trim -%} + {%- if _sc -%}{{- '\n\n' ~ _sc -}}{%- endif -%} + {%- endif -%} + {{- '<|im_end|>\n' -}} +{%- elif _sys_msg is not none -%} + {{- '<|im_start|>system\n' ~ render_content(_sys_msg.content, false, true) | trim ~ '<|im_end|>\n' -}} +{%- endif -%} + +{%- if _compression -%} + {{- '<|im_start|>user\n[Earlier ' ~ _dropped | string ~ ' messages omitted]\n<|im_end|>\n' -}} +{%- endif -%} + +{#- ── Compute last real-user-query index ──────────────────────────────────── -#} +{%- set _last_idx = _msgs | length - 1 -%} +{%- set ns = namespace(found=false, last_query_index=_last_idx) -%} +{%- for message in _msgs[::-1] -%} + {%- if not ns.found and message.role == 'user' -%} + {%- set _rc = render_content(message.content, false) | trim -%} + {%- if not (_rc.startswith('') and _rc.endswith('')) -%} + {%- set ns.found = true -%} + {%- set ns.last_query_index = (_msgs | length - 1) - loop.index0 -%} + {%- endif -%} + {%- endif -%} +{%- endfor -%} +{%- if not ns.found -%} + {{- raise_exception('No user query found in messages.') -}} +{%- endif -%} + +{#- ── Detect tool-relay tail (for generation prompt) ──────────────────────── -#} +{%- set _last_is_tool_relay = false -%} +{%- if _msgs | length > 0 -%} + {%- if _msgs[-1].role == 'tool' -%} + {%- set _last_is_tool_relay = true -%} + {%- elif _msgs[-1].role == 'user' -%} + {%- set _lrc = render_content(_msgs[-1].content, false) | trim -%} + {%- if _lrc.startswith('') and _lrc.endswith('') -%} + {%- set _last_is_tool_relay = true -%} + {%- endif -%} + {%- endif -%} +{%- endif -%} + +{#- ── Main render loop ────────────────────────────────────────────────────── -#} +{%- set ns2 = namespace(prev_role='') -%} +{%- for message in _msgs -%} + {%- set content = render_content(message.content, true) | trim -%} + + {%- if message.role == 'user' -%} + {{- '<|im_start|>user\n' ~ content ~ '<|im_end|>\n' -}} + + {%- elif message.role == 'assistant' -%} + {#- Auto-close unclosed block before -#} + {%- if '' in content and '' in content -%} + {%- set _last_think = content.rfind('') -%} + {%- set _last_close_think = content.rfind('') -%} + {%- set _last_close_thinking = content.rfind('') -%} + {%- set _last_close = _last_close_think if _last_close_think > _last_close_thinking else _last_close_thinking -%} + {%- set _tool_pos = content.find('') -%} + {%- if _last_close < _last_think or _last_close == -1 -%} + {%- if _tool_pos > _last_think -%} + {%- set content = content[:_tool_pos] ~ '\n\n' ~ content[_tool_pos:] -%} + {%- else -%} + {%- set content = content ~ '\n\n' -%} + {%- endif -%} + {%- endif -%} + {%- endif -%} + {#- Extract reasoning_content (supports and ) -#} + {%- set reasoning_content = '' -%} + {%- if message.reasoning_content is defined and message.reasoning_content is not none -%} + {%- if message.reasoning_content is string -%} + {%- set reasoning_content = message.reasoning_content -%} + {%- else -%} + {%- set reasoning_content = message.reasoning_content | string -%} + {%- endif -%} + {%- else -%} + {%- set _think_end = '' -%} + {%- if '' in content -%} + {%- set _think_end = '' -%} + {%- elif '\n' in content -%} + {%- set _think_end = '' -%} + {%- endif -%} + {%- if _think_end and _think_end in content -%} + {%- set reasoning_content = content.split(_think_end)[0].rstrip('\n').split('')[-1].lstrip('\n') -%} + {%- set content = content.split(_think_end)[-1].lstrip('\n') -%} + {%- endif -%} + {%- endif -%} + {%- set reasoning_content = reasoning_content | trim -%} + + {#- Render turn -#} + {#- preserve_thinking=true: preserve only non-empty reasoning blocks -#} + {#- preserve_thinking=false: only include after last query, skip empty -#} + {#- (keeps prefix-cache hits stable — HF Qwen3.5-122B-A10B disc#22) -#} + {%- if reasoning_content and (preserve_thinking or loop.index0 > ns.last_query_index) -%} + {{- '<|im_start|>assistant\n\n' ~ reasoning_content ~ '\n\n\n' ~ content -}} + {%- else -%} + {{- '<|im_start|>assistant\n' ~ content -}} + {%- endif -%} + + {#- Render tool_calls -#} + {%- if message.tool_calls is defined and message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping -%} + {%- for tool_call in message.tool_calls -%} + {%- set tc = tool_call.function if (tool_call.function is defined and tool_call.function is not none) else tool_call -%} + + {%- if loop.first and content | trim -%} + {{- '\n\n' -}} + {%- elif not loop.first -%} + {{- '\n\n' -}} + {%- endif -%} + + {{- '\n\n' -}} + + {%- if tc.arguments is defined and tc.arguments is not none -%} + {%- if tc.arguments is mapping -%} + {%- for k, v in tc.arguments.items() -%} + {{- render_tool_param(k, v) -}} + {%- endfor -%} + {%- elif tc.arguments is string and tc.arguments | trim -%} + {%- set _trimmed = tc.arguments | trim -%} + {%- if _trimmed.startswith('{') -%} + {%- set _parsed = _trimmed | from_json -%} + {%- if _parsed is mapping -%} + {%- for k, v in _parsed.items() -%} + {{- render_tool_param(k, v) -}} + {%- endfor -%} + {%- else -%} + {{- _trimmed -}} + {%- endif -%} + {%- else -%} + {{- _trimmed -}} + {%- endif -%} + {%- endif -%} + {%- endif -%} + {{- '\n' -}} + {%- endfor -%} + {%- endif -%} + {{- '<|im_end|>\n' -}} + + {%- elif message.role == 'tool' -%} + {%- if ns2.prev_role != 'tool' -%} + {{- '<|im_start|>user' -}} + {%- endif -%} + {%- if max_tool_response_chars > 0 and content | length > max_tool_response_chars -%} + {%- set content = content[:max_tool_response_chars] ~ '\n[TRUNCATED original_chars=' ~ (content | length) ~ ' shown_chars=' ~ max_tool_response_chars ~ ']' -%} + {%- endif -%} + {%- set _rid = '' -%} + {%- if message.tool_call_id is defined and message.tool_call_id is not none -%} + {%- set _rid = message.tool_call_id | string -%} + {%- endif -%} + {%- set _err = (message.is_error is defined and message.is_error) -%} + {%- if _rid and _err -%} + {{- '\n\n' ~ content ~ '\n' -}} + {%- elif _rid -%} + {{- '\n\n' ~ content ~ '\n' -}} + {%- elif _err -%} + {{- '\n\n' ~ content ~ '\n' -}} + {%- else -%} + {{- '\n\n' ~ content ~ '\n' -}} + {%- endif -%} + {%- if loop.last or _msgs[loop.index0 + 1].role != 'tool' -%} + {{- '<|im_end|>\n' -}} + {%- endif -%} + + {%- elif message.role == 'system' or message.role == 'developer' -%} + {{- '<|im_start|>system\n' ~ content ~ '<|im_end|>\n' -}} + + {%- else -%} + {{- raise_exception('Unexpected message role: ' ~ message.role) -}} + {%- endif -%} + + {%- set ns2.prev_role = message.role -%} +{%- endfor -%} + +{#- ── Generation prompt ───────────────────────────────────────────────────── -#} +{%- if add_generation_prompt -%} + {{- '<|im_start|>assistant\n' -}} + {%- if not _thinking or _last_is_tool_relay -%} + {{- '\n\n\n\n' -}} + {%- else -%} + {{- '\n' -}} + {%- endif -%} +{%- endif -%} diff --git a/examples/disaggregated/disaggregated_serving/disagg_proxy_pushconnector_demo.py b/examples/disaggregated/disaggregated_serving/disagg_proxy_pushconnector_demo.py new file mode 100644 index 000000000000..9f1a0a7f4135 --- /dev/null +++ b/examples/disaggregated/disaggregated_serving/disagg_proxy_pushconnector_demo.py @@ -0,0 +1,429 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +""" +Push-mode disaggregated prefilling proxy demo. + +Companion to ``disagg_proxy_demo.py`` (pull mode). The client-facing API is +the same; the difference is in how P and D coordinate the KV transfer: + +* Pull mode: proxy forwards P's ``kv_transfer_params`` (including + ``remote_block_ids``) to D, and D pulls KV from P via NIXL READ. +* Push mode: proxy hands D **only** P's coordinates + (``remote_engine_id``, ``remote_host``, ``remote_port``, ``tp_size``) + and the shared ``remote_request_id``. D registers its locally allocated + blocks with P over a NIXL notification; P then pushes the KV to D via + NIXL WRITE. + +Launch multiple vLLM instances configured with ``NixlPushConnector`` and +matching ``engine_id`` / ``side_channel_port``, then start this proxy: + + python3 examples/disaggregated/disaggregated_serving/\ +disagg_proxy_pushconnector_demo.py \ + --model $model_name \ + --prefill localhost:8100 \ + --decode localhost:8200 \ + --prefill-engine-id prefill-engine-001 \ + --prefill-kv-host 10.0.0.1 \ + --prefill-side-channel-port 5600 \ + --prefill-tp-size 1 \ + --port 8000 +""" + +import argparse +import contextlib +import ipaddress +import itertools +import json +import logging +import os +import sys +import uuid +from abc import ABC, abstractmethod +from collections.abc import Callable + +import aiohttp +import uvicorn +from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse, StreamingResponse + +AIOHTTP_TIMEOUT = aiohttp.ClientTimeout(total=6 * 60 * 60) +logger = logging.getLogger() +logging.basicConfig(level=logging.INFO) + + +class SchedulingPolicy(ABC): + @abstractmethod + def schedule(self, cycler: itertools.cycle): + raise NotImplementedError("Scheduling Proxy is not set.") + + +class RoundRobinSchedulingPolicy(SchedulingPolicy): + def schedule(self, cycler: itertools.cycle) -> str: + return next(cycler) + + +class PushProxy: + """Push-mode proxy. + + The structure mirrors the pull-mode ``Proxy`` in + ``disagg_proxy_demo.py``: an APIRouter with ``/v1/completions``, + ``/v1/chat/completions``, ``/status`` and ``/instances/add``, plus + round-robin scheduling across multiple P / D instances. + + Push-specific differences are confined to the request-handling + methods (``create_completion`` / ``create_chat_completion``): + + * D's ``kv_transfer_params`` is built from CLI-provided P + coordinates instead of being derived from P's response. + * P and D requests are issued concurrently — D registers blocks and + waits while P prefills and pushes. + """ + + def __init__( + self, + prefill_instances: list[str], + decode_instances: list[str], + model: str, + scheduling_policy: SchedulingPolicy, + prefill_engine_id: str, + prefill_kv_host: str, + prefill_side_channel_port: int, + prefill_tp_size: int, + custom_create_completion: Callable[[Request], StreamingResponse] | None = None, + custom_create_chat_completion: Callable[[Request], StreamingResponse] + | None = None, + ): + self.prefill_instances = prefill_instances + self.decode_instances = decode_instances + self.prefill_cycler = itertools.cycle(prefill_instances) + self.decode_cycler = itertools.cycle(decode_instances) + self.model = model + self.scheduling_policy = scheduling_policy + + # Push-mode metadata: D needs P's coordinates up-front. Pull mode + # learns these from P's response; push mode uses CLI args because + # D issues its registration before P responds. + self.push_metadata = { + "do_remote_decode": False, + "do_remote_prefill": True, + "remote_engine_id": prefill_engine_id, + "remote_host": prefill_kv_host, + "remote_port": prefill_side_channel_port, + "tp_size": prefill_tp_size, + } + + self.custom_create_completion = custom_create_completion + self.custom_create_chat_completion = custom_create_chat_completion + self.router = APIRouter() + self.setup_routes() + + # ── routes ──────────────────────────────────────────────────────── # + + def setup_routes(self): + self.router.post( + "/v1/completions", dependencies=[Depends(self.validate_json_request)] + )( + self.custom_create_completion + if self.custom_create_completion + else self.create_completion + ) + self.router.post( + "/v1/chat/completions", dependencies=[Depends(self.validate_json_request)] + )( + self.custom_create_chat_completion + if self.custom_create_chat_completion + else self.create_chat_completion + ) + self.router.get("/status", response_class=JSONResponse)(self.get_status) + + async def validate_json_request(self, raw_request: Request): + content_type = raw_request.headers.get("content-type", "").lower() + if content_type != "application/json": + raise HTTPException( + status_code=415, + detail="Unsupported Media Type: Only 'application/json' is allowed", + ) + + # ── HTTP forwarding ─────────────────────────────────────────────── # + + async def forward_request(self, url, data, headers, use_chunked=True): + async with aiohttp.ClientSession(timeout=AIOHTTP_TIMEOUT) as session: + try: + async with session.post( + url=url, json=data, headers=headers + ) as response: + if 200 <= response.status < 300 or 400 <= response.status < 500: + if use_chunked: + async for chunk_bytes in response.content.iter_chunked( + 1024 + ): + yield chunk_bytes + else: + yield await response.read() + else: + error_content = await response.text() + with contextlib.suppress(json.JSONDecodeError): + error_content = json.loads(error_content) + logger.error( + "Request failed with status %s: %s", + response.status, + error_content, + ) + raise HTTPException( + status_code=response.status, + detail=f"Request failed with status {response.status}: " + f"{error_content}", + ) + except aiohttp.ClientError as e: + logger.error("ClientError occurred: %s", str(e)) + raise HTTPException( + status_code=502, + detail="Bad Gateway: Error communicating with upstream server.", + ) from e + except Exception as e: + logger.error("Unexpected error: %s", str(e)) + raise HTTPException(status_code=500, detail=str(e)) from e + + def schedule(self, cycler: itertools.cycle) -> str: + return self.scheduling_policy.schedule(cycler) + + async def get_status(self): + return { + "mode": "push", + "prefill_node_count": len(self.prefill_instances), + "decode_node_count": len(self.decode_instances), + "prefill_nodes": self.prefill_instances, + "decode_nodes": self.decode_instances, + "prefill_engine_id": self.push_metadata["remote_engine_id"], + "prefill_kv_host": self.push_metadata["remote_host"], + "prefill_side_channel_port": self.push_metadata["remote_port"], + "prefill_tp_size": self.push_metadata["tp_size"], + } + + # ── push-mode request handling ──────────────────────────────────── # + + def _build_decode_kv_params(self, request_id: str) -> dict: + """Push-mode kv_transfer_params for D. + + ``remote_block_ids`` is intentionally omitted: D allocates its + own blocks and registers them with P; P determines the + prefill-side block IDs and ships them via the WRITE. + """ + params = self.push_metadata.copy() + params["remote_request_id"] = request_id + return params + + def _common_headers(self, request_id: str) -> dict: + h = {"X-Request-Id": request_id} + api_key = os.environ.get("OPENAI_API_KEY") + if api_key: + h["Authorization"] = f"Bearer {api_key}" + return h + + async def _push_completion(self, raw_request: Request, path: str): + """Shared body for /v1/completions and /v1/chat/completions. + + Push mode fires P and D concurrently: + * P runs a normal prefill (max_tokens=1, do_remote_decode=True). + * D runs the decode (do_remote_prefill=True, no remote_block_ids). + + D blocks waiting for P's WRITE; the response streamed back to the + client is the decode output from D. + """ + request = await raw_request.json() + request_id = str(uuid.uuid4()) + + # Prefill leg (max_tokens=1, signals P to keep KV around for D). + prefill_request = request.copy() + prefill_request["max_tokens"] = 1 + if "max_completion_tokens" in prefill_request: + prefill_request["max_completion_tokens"] = 1 + prefill_request["kv_transfer_params"] = { + "do_remote_decode": True, + "do_remote_prefill": False, + "remote_engine_id": None, + "remote_block_ids": None, + "remote_host": None, + "remote_port": None, + } + + # Decode leg (push mode: no remote_block_ids). + decode_request = request.copy() + decode_request["kv_transfer_params"] = self._build_decode_kv_params(request_id) + + prefill_instance = self.schedule(self.prefill_cycler) + decode_instance = self.schedule(self.decode_cycler) + headers = self._common_headers(request_id) + + # Fire prefill; we don't read its body but must drain the + # connection so the upstream server can free its slot. + async for _ in self.forward_request( + f"http://{prefill_instance}{path}", prefill_request, headers + ): + continue + + generator = self.forward_request( + f"http://{decode_instance}{path}", decode_request, headers + ) + return StreamingResponse(generator) + + async def create_completion(self, raw_request: Request): + try: + return await self._push_completion(raw_request, "/v1/completions") + except HTTPException: + raise + except Exception: + exc_info = sys.exc_info() + print("Error occurred in disagg push proxy server") + print(exc_info) + raise + + async def create_chat_completion(self, raw_request: Request): + try: + return await self._push_completion(raw_request, "/v1/chat/completions") + except HTTPException: + raise + except Exception: + exc_info = sys.exc_info() + error_messages = [str(e) for e in exc_info if e] + print("Error occurred in disagg push proxy server") + print(error_messages) + return StreamingResponse( + content=iter(error_messages), media_type="text/event-stream" + ) + + +class PushProxyServer: + def __init__( + self, + args: argparse.Namespace, + scheduling_policy: SchedulingPolicy | None = None, + create_completion: Callable[[Request], StreamingResponse] | None = None, + create_chat_completion: Callable[[Request], StreamingResponse] | None = None, + ): + self.validate_parsed_serve_args(args) + self.port = args.port + self.proxy_instance = PushProxy( + prefill_instances=[] if args.prefill is None else args.prefill, + decode_instances=[] if args.decode is None else args.decode, + model=args.model, + scheduling_policy=( + scheduling_policy + if scheduling_policy is not None + else RoundRobinSchedulingPolicy() + ), + prefill_engine_id=args.prefill_engine_id, + prefill_kv_host=args.prefill_kv_host, + prefill_side_channel_port=args.prefill_side_channel_port, + prefill_tp_size=args.prefill_tp_size, + custom_create_completion=create_completion, + custom_create_chat_completion=create_chat_completion, + ) + + def validate_parsed_serve_args(self, args: argparse.Namespace): + if not args.prefill: + raise ValueError("Please specify at least one prefill node.") + if not args.decode: + raise ValueError("Please specify at least one decode node.") + if not args.prefill_engine_id: + raise ValueError( + "--prefill-engine-id is required in push mode (it must match " + "the engine_id passed to the prefill vLLM instance via " + "--kv-transfer-config)." + ) + if not args.prefill_kv_host: + raise ValueError( + "--prefill-kv-host is required in push mode (the IP / host " + "that the prefill vLLM advertises on its NIXL side channel)." + ) + self.validate_instances(args.prefill) + self.validate_instances(args.decode) + + def validate_instances(self, instances: list): + for instance in instances: + if len(instance.split(":")) != 2: + raise ValueError(f"Invalid instance format: {instance}") + host, port = instance.split(":") + try: + if host != "localhost": + ipaddress.ip_address(host) + port = int(port) + if not (0 < port < 65536): + raise ValueError(f"Invalid port number in instance: {instance}") + except Exception as e: + raise ValueError(f"Invalid instance {instance}: {str(e)}") from e + + def run_server(self): + app = FastAPI() + app.include_router(self.proxy_instance.router) + config = uvicorn.Config(app, port=self.port, loop="uvloop") + server = uvicorn.Server(config) + server.run() + + +def parse_args(): + parser = argparse.ArgumentParser("vLLM disaggregated push-mode proxy server.") + parser.add_argument("--model", "-m", type=str, required=True, help="Model name") + + parser.add_argument( + "--prefill", + "-p", + type=str, + nargs="+", + help="List of prefill node URLs (host:port)", + ) + + parser.add_argument( + "--decode", + "-d", + type=str, + nargs="+", + help="List of decode node URLs (host:port)", + ) + + parser.add_argument( + "--port", + type=int, + default=8000, + help="Server port number", + ) + + # Push-mode specific: P's coordinates that D needs in advance. + parser.add_argument( + "--prefill-engine-id", + type=str, + required=True, + help=( + "engine_id of the prefill vLLM instance (must match " + "--kv-transfer-config engine_id on the prefill server)" + ), + ) + parser.add_argument( + "--prefill-kv-host", + type=str, + required=True, + help=( + "IP / host the prefill vLLM advertises on its NIXL side " + "channel (VLLM_NIXL_SIDE_CHANNEL_HOST)" + ), + ) + parser.add_argument( + "--prefill-side-channel-port", + type=int, + default=5600, + help="NIXL side channel port on the prefill node " + "(VLLM_NIXL_SIDE_CHANNEL_PORT, default 5600)", + ) + parser.add_argument( + "--prefill-tp-size", + type=int, + default=1, + help="Tensor parallel size of the prefill vLLM instance", + ) + return parser.parse_args() + + +if __name__ == "__main__": + args = parse_args() + proxy_server = PushProxyServer(args=args) + proxy_server.run_server() diff --git a/examples/generate/multimodal/vision_language_offline.py b/examples/generate/multimodal/vision_language_offline.py index a7df5b00c3b8..1b3741a3e42e 100644 --- a/examples/generate/multimodal/vision_language_offline.py +++ b/examples/generate/multimodal/vision_language_offline.py @@ -2533,15 +2533,17 @@ def run_tarsier2(questions: list[str], modality: str) -> ModelRequestData: MODELS_SUPPORT_VIT_CUDA_GRAPH = [ "llama4", - "internvl_chat", + "qwen2_vl", "qwen2_5_vl", "qwen3_vl", "qwen3_vl_moe", - "qwen2_vl", + "kimi_vl", "qwen3_5", "qwen3_5_moe", + "internvl_chat", "stepvl", "glm4_1v", + "deepseek_ocr", ] diff --git a/examples/tool_chat_template_gemma4.jinja b/examples/tool_chat_template_gemma4.jinja index ef765823106a..6ce01e6479a0 100644 --- a/examples/tool_chat_template_gemma4.jinja +++ b/examples/tool_chat_template_gemma4.jinja @@ -116,7 +116,9 @@ } {%- endmacro -%} {%- macro format_argument(argument, escape_keys=True) -%} - {%- if argument is string -%} + {%- if argument is none -%} + {{- 'null' -}} + {%- elif argument is string -%} {{- '<|"|>' + argument + '<|"|>' -}} {%- elif argument is boolean -%} {{- 'true' if argument else 'false' -}} @@ -172,18 +174,21 @@ {{- '' -}} {%- endmacro -%} -{%- set ns = namespace(prev_message_type=None) -%} +{#- ===== SETUP ===== -#} +{%- set ns = namespace(prev_message_type=None, prev_non_tool_role=None) -%} {%- set loop_messages = messages -%} +{%- set enable_thinking = enable_thinking | default(false) -%} +{%- set preserve_thinking = preserve_thinking | default(false) -%} {{- bos_token -}} {#- Handle System/Tool Definitions Block -#} -{%- if (enable_thinking is defined and enable_thinking) or tools or messages[0]['role'] in ['system', 'developer'] -%} +{%- if enable_thinking or tools or (messages and messages[0]['role'] in ['system', 'developer']) -%} {{- '<|turn>system\n' -}} {#- Inject Thinking token at the very top of the FIRST system turn -#} - {%- if enable_thinking is defined and enable_thinking -%} + {%- if enable_thinking -%} {{- '<|think|>\n' -}} {%- set ns.prev_message_type = 'think' -%} {%- endif -%} - {%- if messages[0]['role'] in ['system', 'developer'] -%} + {%- if messages and messages[0]['role'] in ['system', 'developer'] -%} {%- if messages[0]['content'] is string -%} {{- messages[0]['content'] | trim -}} {%- elif messages[0]['content'] is sequence -%} @@ -217,31 +222,24 @@ {%- if message['role'] != 'tool' -%} {%- set ns.prev_message_type = None -%} {%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%} - {#- Detect continuation: suppress duplicate <|turn>model when previous non-tool message was also assistant -#} - {%- set prev_nt = namespace(role=None, found=false) -%} - {%- if loop.index0 > 0 -%} - {%- for j in range(loop.index0 - 1, -1, -1) -%} - {%- if not prev_nt.found -%} - {%- if loop_messages[j]['role'] != 'tool' -%} - {%- set prev_nt.role = loop_messages[j]['role'] -%} - {%- set prev_nt.found = true -%} - {%- endif -%} - {%- endif -%} - {%- endfor -%} - {%- endif -%} - {%- set continue_same_model_turn = (role == 'model' and prev_nt.role == 'assistant') -%} + {#- Detect continuation using tracked state — O(1) instead of O(n) backward scan -#} + {%- set continue_same_model_turn = (role == 'model' and ns.prev_non_tool_role == 'assistant') -%} {%- if not continue_same_model_turn -%} {{- '<|turn>' + role + '\n' }} + {%- if role == 'model' and not enable_thinking and not (message.get('reasoning') or message.get('reasoning_content')) -%} + {{- '<|channel>thought\n' -}} + {%- endif -%} {%- endif -%} {#- Render reasoning/reasoning_content as thinking channel -#} {%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%} - {%- if thinking_text and loop.index0 > ns_turn.last_user_idx and message.get('tool_calls') -%} + {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or preserve_thinking -%} + {%- if thinking_text and thinking_gate -%} {{- '<|channel>thought\n' + thinking_text + '\n' -}} {%- endif -%} - {%- if message['tool_calls'] -%} - {%- for tool_call in message['tool_calls'] -%} + {%- if message.get('tool_calls') -%} + {%- for tool_call in message.get('tool_calls') -%} {%- set function = tool_call['function'] -%} {{- '<|tool_call>call:' + function['name'] + '{' -}} {%- if function['arguments'] is mapping -%} @@ -251,8 +249,13 @@ {%- set ns_args.found_first = true -%} {{- key -}}:{{- format_argument(value, escape_keys=False) -}} {%- endfor -%} - {%- elif function['arguments'] is string -%} - {{- function['arguments'] -}} + {%- elif function['arguments'] is none -%} + {%- else -%} + {{- raise_exception( + "chat_template: tool_calls[].function.arguments must be a " + "JSON object (mapping), not a string. Deserialize arguments " + "before passing to the template." + ) -}} {%- endif -%} {{- '}' -}} {%- endfor -%} @@ -262,7 +265,7 @@ {%- set ns_tr_out = namespace(flag=false) -%} {%- if message.get('tool_responses') -%} {#- Legacy: tool_responses embedded on the assistant message (Google/Gemma native) -#} - {%- for tool_response in message['tool_responses'] -%} + {%- for tool_response in message.get('tool_responses') -%} {{- format_tool_response_block(tool_response['name'] | default('unknown', true), tool_response['response']) -}} {%- set ns_tr_out.flag = true -%} {%- set ns.prev_message_type = 'tool_response' -%} @@ -277,8 +280,8 @@ {%- else -%} {%- set follow = loop_messages[k] -%} {#- Resolve tool_call_id to function name -#} - {%- set ns_tname = namespace(name=follow.get('name') | default('unknown', true)) -%} - {%- for tc in message['tool_calls'] -%} + {%- set ns_tname = namespace(name=follow.get('name') or 'unknown') -%} + {%- for tc in message.get('tool_calls') -%} {%- if tc.get('id') == follow.get('tool_call_id') -%} {%- set ns_tname.name = tc['function']['name'] -%} {%- endif -%} @@ -296,9 +299,9 @@ {%- endfor -%} {{- format_tool_response_block(ns_tname.name, ns_txt.s) -}} {%- for part in tool_body -%} - {%- if part.get('type') == 'image' -%} + {%- if part.get('type') in ['image', 'image_url'] -%} {{- '<|image|>' -}} - {%- elif part.get('type') == 'audio' -%} + {%- elif part.get('type') in ['audio', 'input_audio'] -%} {{- '<|audio|>' -}} {%- elif part.get('type') == 'video' -%} {{- '<|video|>' -}} @@ -314,29 +317,26 @@ {%- endif -%} {%- set captured_content -%} - {%- if message['content'] is string -%} + {%- if message.get('content') is string -%} {%- if role == 'model' -%} {{- strip_thinking(message['content']) -}} {%- else -%} {{- message['content'] | trim -}} {%- endif -%} - {%- elif message['content'] is sequence -%} + {%- elif message.get('content') is sequence -%} {%- for item in message['content'] -%} - {%- if item['type'] == 'text' -%} + {%- if item.get('type') == 'text' -%} {%- if role == 'model' -%} {{- strip_thinking(item['text']) -}} {%- else -%} {{- item['text'] | trim -}} {%- endif -%} - {%- elif item['type'] == 'image' -%} + {%- elif item.get('type') in ['image', 'image_url'] -%} {{- '<|image|>' -}} - {%- set ns.prev_message_type = 'image' -%} - {%- elif item['type'] == 'audio' -%} + {%- elif item.get('type') in ['audio', 'input_audio'] -%} {{- '<|audio|>' -}} - {%- set ns.prev_message_type = 'audio' -%} - {%- elif item['type'] == 'video' -%} + {%- elif item.get('type') == 'video' -%} {{- '<|video|>' -}} - {%- set ns.prev_message_type = 'video' -%} {%- endif -%} {%- endfor -%} {%- endif -%} @@ -345,19 +345,43 @@ {{- captured_content -}} {%- set has_content = captured_content | trim | length > 0 -%} + {#- Forward-scan: find next non-tool message role for continuation detection -#} + {%- set next_nt = namespace(role=None, found=false) -%} + {%- for j in range(loop.index0 + 1, loop_messages | length) -%} + {%- if not next_nt.found -%} + {%- if loop_messages[j]['role'] != 'tool' -%} + {%- set next_nt.role = loop_messages[j]['role'] -%} + {%- set next_nt.found = true -%} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + + {%- set continues_into_next = ( + role == 'model' + and next_nt.role == 'assistant' + and (not message.get('tool_calls') or ns_tr_out.flag) + ) -%} + {%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%} {{- '<|tool_response>' -}} + {%- elif continues_into_next -%} + {{- '\n' -}} {%- elif not (ns_tr_out.flag and not has_content) -%} {{- '\n' -}} {%- endif -%} + + {#- Track previous non-tool role for next iteration (avoids O(n) backward scan) -#} + {%- set ns.prev_non_tool_role = message['role'] -%} {%- endif -%} {%- endfor -%} {%- if add_generation_prompt -%} {%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%} {{- '<|turn>model\n' -}} - {%- if not enable_thinking | default(false) -%} + {%- if not enable_thinking -%} {{- '<|channel>thought\n' -}} {%- endif -%} + {%- elif ns.prev_message_type == 'tool_response' and enable_thinking -%} + {{- '<|channel>thought\n' -}} {%- endif -%} -{%- endif -%} \ No newline at end of file +{%- endif -%} diff --git a/pyproject.toml b/pyproject.toml index c782cc326bc1..031f8d1a0a28 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -162,6 +162,8 @@ dout = "dout" Pn = "Pn" arange = "arange" thw = "thw" +# temporal position ids (parallels hpos/wpos in vision RoPE) +tpos = "tpos" subtile = "subtile" HSA = "HSA" setp = "setp" diff --git a/requirements/common.txt b/requirements/common.txt index d6e2031f534c..fde1ba4f0c9e 100644 --- a/requirements/common.txt +++ b/requirements/common.txt @@ -25,13 +25,13 @@ outlines_core == 0.2.14 # required for outlines backend disk cache diskcache == 5.6.3 lark == 1.2.2 -xgrammar >= 0.2.0, < 1.0.0; platform_machine == "x86_64" or platform_machine == "aarch64" or platform_machine == "arm64" or platform_machine == "s390x" or platform_machine == "ppc64le" +xgrammar >= 0.2.1, < 1.0.0; platform_machine == "x86_64" or platform_machine == "aarch64" or platform_machine == "arm64" or platform_machine == "s390x" or platform_machine == "ppc64le" typing_extensions >= 4.10 filelock >= 3.16.1 # need to contain https://github.com/tox-dev/filelock/pull/317 partial-json-parser # used for parsing partial JSON outputs +jsonschema >= 4.23.0 # required for MiniMax M3 tool schema validation pyzmq >= 25.0.0 msgspec -gguf >= 0.17.0 mistral_common[image] >= 1.11.3 opencv-python-headless >= 4.13.0 # required for video IO pyyaml diff --git a/requirements/kv_connectors.txt b/requirements/kv_connectors.txt index 7a5b5f25c37a..e0d494e9f214 100644 --- a/requirements/kv_connectors.txt +++ b/requirements/kv_connectors.txt @@ -2,5 +2,5 @@ lmcache >= 0.3.9 # CuPy 14.1.0 imports pytest from cupy.testing._random. Use <14.1.0 # until a fixed newer release is verified for runtime images. cupy-cuda13x < 14.1.0 -nixl >= 1.1.0 # Required for disaggregated prefill +nixl == 1.2.0 # Required for disaggregated prefill mooncake-transfer-engine >= 0.3.8 diff --git a/requirements/test/cuda.txt b/requirements/test/cuda.txt index a3e1466c763a..c6d9ed24adbf 100644 --- a/requirements/test/cuda.txt +++ b/requirements/test/cuda.txt @@ -360,6 +360,7 @@ jsonpointer==3.0.0 # via jsonschema jsonschema==4.23.0 # via + # -c requirements/common.txt # hypothesis-jsonschema # mistral-common # ray diff --git a/requirements/test/rocm.txt b/requirements/test/rocm.txt index ce18ce456cc2..879a32864442 100644 --- a/requirements/test/rocm.txt +++ b/requirements/test/rocm.txt @@ -279,10 +279,6 @@ genai-perf==0.0.16 # via -r requirements/test/rocm.in genson==1.3.0 # via datamodel-code-generator -gguf==0.18.0 - # via - # -c requirements/common.txt - # -r requirements/test/../common.txt google-api-core==2.30.0 # via # google-cloud-core @@ -443,6 +439,8 @@ jsonpointer==3.1.0 # via jsonschema jsonschema==4.26.0 # via + # -c requirements/common.txt + # -r requirements/test/../common.txt # hypothesis-jsonschema # mcp # mistral-common @@ -589,7 +587,6 @@ numpy==2.2.6 # evaluate # fastparquet # genai-perf - # gguf # imagehash # imageio # librosa @@ -959,7 +956,6 @@ pyyaml==6.0.3 # datamodel-code-generator # datasets # genai-perf - # gguf # huggingface-hub # lm-format-enforcer # optuna @@ -1004,7 +1000,6 @@ requests==2.32.5 # datasets # docker # evaluate - # gguf # google-api-core # google-cloud-storage # gpt-oss @@ -1231,7 +1226,6 @@ tqdm==4.67.3 # -r requirements/test/../common.txt # datasets # evaluate - # gguf # huggingface-hub # lm-eval # mteb @@ -1367,7 +1361,7 @@ word2number==1.1 # via lm-eval wrapt==2.1.2 # via smart-open -xgrammar==0.2.0 +xgrammar==0.2.1 # via # -c requirements/common.txt # -r requirements/test/../common.txt diff --git a/requirements/test/xpu.in b/requirements/test/xpu.in index a828867845f2..161e2c6871f8 100644 --- a/requirements/test/xpu.in +++ b/requirements/test/xpu.in @@ -13,7 +13,7 @@ pytest-shard absl-py accelerate arctic-inference -lm_eval[api] +lm_eval[api]>=0.4.12 modelscope # --- Audio Processing --- diff --git a/requirements/test/xpu.txt b/requirements/test/xpu.txt index 6d5435462ff0..1b1f3c91c5e0 100644 --- a/requirements/test/xpu.txt +++ b/requirements/test/xpu.txt @@ -33,7 +33,6 @@ arctic-inference==0.1.1 attrs==26.1.0 # via # aiohttp - # jsonlines # jsonschema # referencing audioread==3.0.1 @@ -225,10 +224,9 @@ joblib==1.5.3 # librosa # nltk # scikit-learn -jsonlines==4.0.0 - # via lm-eval jsonschema==4.26.0 # via + # -c requirements/common.txt # hypothesis-jsonschema # mistral-common # schemathesis @@ -246,7 +244,7 @@ librosa==0.10.2.post1 # via -r requirements/test/xpu.in llvmlite==0.47.0 # via numba -lm-eval==0.4.11 +lm-eval==0.4.12 # via -r requirements/test/xpu.in lxml==6.0.2 # via @@ -733,5 +731,3 @@ xxhash==3.6.0 # evaluate yarl==1.23.0 # via aiohttp -zstandard==0.25.0 - # via lm-eval diff --git a/requirements/tpu.txt b/requirements/tpu.txt index ea2c24bba0f0..d9b9f42beba4 100644 --- a/requirements/tpu.txt +++ b/requirements/tpu.txt @@ -12,4 +12,4 @@ ray[data] setuptools==78.1.0 setuptools-rust>=1.9.0 nixl==0.3.0 -tpu-inference==0.21.0 +tpu-inference==0.22.1 diff --git a/requirements/xpu.txt b/requirements/xpu.txt index 33a808866c4d..f17e2281f7a8 100644 --- a/requirements/xpu.txt +++ b/requirements/xpu.txt @@ -16,5 +16,5 @@ torch==2.12.0 torchaudio torchvision -auto_round_lib>=0.13.0 +auto_round_lib>=0.13.3 vllm_xpu_kernels @ https://github.com/vllm-project/vllm-xpu-kernels/releases/download/v0.1.9.1/vllm_xpu_kernels-0.1.9.1-cp38-abi3-manylinux_2_28_x86_64.whl diff --git a/rust/Cargo.lock b/rust/Cargo.lock index c1477092b915..0369dc8d94b6 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -5804,6 +5804,7 @@ dependencies = [ "enum-as-inner", "expect-test", "futures", + "parking_lot", "rmp-serde", "serde", "serde_json", diff --git a/rust/Cargo.toml b/rust/Cargo.toml index c61fd9c19ecf..455e660bcfee 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -105,7 +105,7 @@ tonic-prost = "0.14.5" tonic-prost-build = "0.14.5" tool-parser = "1.2.0" tower = { version = "0.5.3", features = ["util"] } -tower-http = { version = "0.6.8", features = ["trace"] } +tower-http = { version = "0.6.8", features = ["cors", "trace"] } tracing = { version = "0.1.44", features = ["release_max_level_debug"] } tracing-futures = { version = "0.2.5", features = ["futures-03"] } tracing-subscriber = { version = "0.3.20", features = ["env-filter", "fmt"] } diff --git a/rust/src/chat/src/lib.rs b/rust/src/chat/src/lib.rs index 63b4cbdbf422..012307758ca6 100644 --- a/rust/src/chat/src/lib.rs +++ b/rust/src/chat/src/lib.rs @@ -145,8 +145,8 @@ impl ChatLlm { self.text.tokenizer_vocab_size() } - /// Model vocabulary size, else `None`. - pub fn model_vocab_size(&self) -> Option { + /// Model vocabulary size from the model config. + pub fn model_vocab_size(&self) -> usize { self.text.model_vocab_size() } @@ -235,6 +235,12 @@ impl ChatLlm { Ok(token_ids) } + /// Abort in-flight requests by their external (user-supplied) request ids. + pub async fn abort(&self, external_ids: &[String]) -> Result<()> { + self.text.abort(external_ids).await?; + Ok(()) + } + /// Shut down the underlying LLM client and its background tasks. pub async fn shutdown(self) -> Result<()> { self.text.shutdown().await?; @@ -271,7 +277,7 @@ mod tests { ) .unwrap_err(); - expect_test::expect!["tool parser `definitely_missing_tool_parser` is not registered (choose from: deepseek_v3, deepseek_v31, deepseek_v32, deepseek_v4, gemma4, glm45, glm47, hermes, hy_v3, internlm, kimi_k2, llama3_json, llama4_json, minimax_m2, mistral, phi4_mini_json, qwen3_coder, qwen3_xml)"].assert_eq(&error.to_report_string()); + expect_test::expect!["tool parser `definitely_missing_tool_parser` is not registered (choose from: deepseek_v3, deepseek_v31, deepseek_v32, deepseek_v4, gemma4, glm45, glm47, granite4, hermes, hy_v3, internlm, kimi_k2, llama3_json, llama4_json, minimax_m2, minimax_m3, mistral, phi4_mini_json, qwen3_coder, qwen3_xml)"].assert_eq(&error.to_report_string()); } #[test] @@ -282,6 +288,6 @@ mod tests { ) .unwrap_err(); - expect_test::expect!["reasoning parser `definitely_missing_reasoning_parser` is not registered (choose from: cohere_cmd, deepseek_r1, deepseek_v3, deepseek_v4, gemma4, glm45, kimi, kimi_k2, minimax_m2, nemotron_v3, qwen3, seed_oss, step3, step3p5)"].assert_eq(&error.to_report_string()); + expect_test::expect!["reasoning parser `definitely_missing_reasoning_parser` is not registered (choose from: cohere_cmd, deepseek_r1, deepseek_v3, deepseek_v4, gemma4, glm45, kimi, kimi_k2, minimax_m2, minimax_m3, nemotron_v3, qwen3, seed_oss, step3, step3p5)"].assert_eq(&error.to_report_string()); } } diff --git a/rust/src/chat/src/output/default/mod.rs b/rust/src/chat/src/output/default/mod.rs index 40526a9e84ce..bebcf8839d52 100644 --- a/rust/src/chat/src/output/default/mod.rs +++ b/rust/src/chat/src/output/default/mod.rs @@ -37,6 +37,7 @@ trait_set! { pub struct DefaultChatOutputProcessor { reasoning_parser: Option>, tool_parser: Option>, + parallel_tool_calls: bool, } impl DefaultChatOutputProcessor { @@ -74,6 +75,7 @@ impl DefaultChatOutputProcessor { Ok(Self { reasoning_parser, tool_parser, + parallel_tool_calls: request.parallel_tool_calls, }) } @@ -86,6 +88,7 @@ impl DefaultChatOutputProcessor { Self { reasoning_parser: None, tool_parser: None, + parallel_tool_calls: true, } } @@ -159,7 +162,7 @@ impl ChatOutputProcessor for DefaultChatOutputProcessor { fn process(self: Box, decoded: DynDecodedTextEventStream) -> Result { let reasoning = reasoning_event_stream(decoded, self.reasoning_parser); let tool = tool_event_stream(reasoning, self.tool_parser); - let structured = structured_chat_event_stream(tool); + let structured = structured_chat_event_stream(tool, self.parallel_tool_calls); Ok(structured.boxed()) } diff --git a/rust/src/chat/src/output/default/tool.rs b/rust/src/chat/src/output/default/tool.rs index c216b93f7402..665972f14862 100644 --- a/rust/src/chat/src/output/default/tool.rs +++ b/rust/src/chat/src/output/default/tool.rs @@ -473,7 +473,7 @@ mod tests { }))); let parser = DeepSeekV4ToolParser::create(&deepseek_v4_test_tools()).unwrap(); let assistant_events = tool_event_stream(stream::iter(events), Some(parser)); - let chat_events = structured_chat_event_stream(assistant_events); + let chat_events = structured_chat_event_stream(assistant_events, true); ChatEventStream::new("req_deepseek_v4".to_string(), Box::pin(chat_events)) .collect_message() @@ -717,9 +717,10 @@ mod tests { let message = ChatEventStream::new( "req_fallback".to_string(), - Box::pin(structured_chat_event_stream(stream::iter( - events.into_iter().map(Ok), - ))), + Box::pin(structured_chat_event_stream( + stream::iter(events.into_iter().map(Ok)), + true, + )), ) .collect_message() .await @@ -968,9 +969,10 @@ mod tests { )); let collected = ChatEventStream::new( "req_final_only".to_string(), - Box::pin(structured_chat_event_stream(stream::iter( - events.into_iter().map(Ok), - ))), + Box::pin(structured_chat_event_stream( + stream::iter(events.into_iter().map(Ok)), + true, + )), ) .collect_message() .await diff --git a/rust/src/chat/src/output/harmony/mod.rs b/rust/src/chat/src/output/harmony/mod.rs index 7a043374e555..4209dc0735cb 100644 --- a/rust/src/chat/src/output/harmony/mod.rs +++ b/rust/src/chat/src/output/harmony/mod.rs @@ -35,6 +35,7 @@ use crate::request::ChatRequest; pub struct HarmonyChatOutputProcessor { encoding: &'static HarmonyEncoding, tool_calls_enabled: bool, + parallel_tool_calls: bool, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -76,6 +77,7 @@ impl HarmonyChatOutputProcessor { Ok(Self { encoding: harmony_encoding()?, tool_calls_enabled: request.tool_parsing_enabled(), + parallel_tool_calls: request.parallel_tool_calls, }) } } @@ -110,7 +112,11 @@ impl ChatOutputProcessor for HarmonyChatOutputProcessor { fn process(self: Box, decoded: DynDecodedTextEventStream) -> Result { let assistant = harmony_assistant_event_stream(decoded, self.encoding, self.tool_calls_enabled); - Ok(crate::output::structured::structured_chat_event_stream(assistant).boxed()) + Ok(crate::output::structured::structured_chat_event_stream( + assistant, + self.parallel_tool_calls, + ) + .boxed()) } } diff --git a/rust/src/chat/src/output/structured.rs b/rust/src/chat/src/output/structured.rs index 5cbb9f8093ca..4be7425d9015 100644 --- a/rust/src/chat/src/output/structured.rs +++ b/rust/src/chat/src/output/structured.rs @@ -53,16 +53,22 @@ struct StructuredEventState { open_tool_call: Option, /// Next OpenAI-compatible tool-call ordinal. next_tool_call_index: usize, + /// Whether more than one tool call may be surfaced northbound. + parallel_tool_calls: bool, + /// Whether the current tool-call parse is being suppressed. + suppressing_tool_call: bool, } impl StructuredEventState { /// Create one fresh assembly state for a new streamed response. - fn new() -> Self { + fn new(parallel_tool_calls: bool) -> Self { Self { message: AssistantMessage::default(), open_text_block: None, open_tool_call: None, next_tool_call_index: 0, + parallel_tool_calls, + suppressing_tool_call: false, } } @@ -98,6 +104,12 @@ impl StructuredEventState { let index = self.next_tool_call_index; self.next_tool_call_index += 1; + if !self.parallel_tool_calls && index >= 1 { + self.suppressing_tool_call = true; + return Ok(events); + } + + self.suppressing_tool_call = false; self.open_tool_call = Some(OpenToolCall { index, id: id.clone(), @@ -110,6 +122,10 @@ impl StructuredEventState { /// Append one incremental tool-call arguments delta. fn push_tool_call_arguments(&mut self, delta: String) -> Result> { + if self.suppressing_tool_call { + return Ok(Vec::new()); + } + let mut events = Vec::new(); let Some(open_tool_call) = self.open_tool_call.as_mut() else { return Err(Error::ToolCallStreamInvariant { @@ -207,6 +223,11 @@ impl StructuredEventState { /// Finalize the currently open tool call, if present. fn close_open_tool_call(&mut self, events: &mut Vec) { + if self.suppressing_tool_call { + self.suppressing_tool_call = false; + return; + } + let Some(open_tool_call) = self.open_tool_call.take() else { return; }; @@ -229,11 +250,12 @@ impl StructuredEventState { #[try_stream] pub(crate) async fn structured_chat_event_stream( stream: impl AssistantEventStream, + parallel_tool_calls: bool, mut y: TryYielder, ) -> Result<()> { pin_mut!(stream); - let mut state = StructuredEventState::new(); + let mut state = StructuredEventState::new(parallel_tool_calls); while let Some(event) = stream.next().await.transpose()? { match event { @@ -315,7 +337,7 @@ mod tests { }), ]); - let events = structured_chat_event_stream(events) + let events = structured_chat_event_stream(events, true) .collect::>() .await .into_iter() @@ -369,7 +391,7 @@ mod tests { }), ]); - let events = structured_chat_event_stream(events) + let events = structured_chat_event_stream(events, true) .collect::>() .await .into_iter() @@ -420,7 +442,7 @@ mod tests { }), ]); - let events = structured_chat_event_stream(events) + let events = structured_chat_event_stream(events, true) .collect::>() .await .into_iter() @@ -471,7 +493,7 @@ mod tests { }), ]); - let events = structured_chat_event_stream(events) + let events = structured_chat_event_stream(events, true) .collect::>() .await .into_iter() @@ -499,7 +521,7 @@ mod tests { delta: "{}".to_string(), })]); - let err = structured_chat_event_stream(events) + let err = structured_chat_event_stream(events, true) .collect::>() .await .into_iter() @@ -509,4 +531,56 @@ mod tests { assert!(matches!(err, Error::ToolCallStreamInvariant { .. })); } + + #[tokio::test] + async fn structured_stream_suppresses_later_tool_calls_when_parallel_disabled() { + let events = stream::iter(vec![ + Ok(AssistantEvent::ToolCallStart { + id: "call_1".to_string(), + name: "first".to_string(), + }), + Ok(AssistantEvent::ToolCallArgumentsDelta { + delta: r#"{"a":1}"#.to_string(), + }), + Ok(AssistantEvent::ToolCallStart { + id: "call_2".to_string(), + name: "second".to_string(), + }), + Ok(AssistantEvent::ToolCallArgumentsDelta { + delta: r#"{"b":2}"#.to_string(), + }), + Ok(AssistantEvent::Done { + usage: vllm_llm::TokenUsage { + prompt_token_count: 1, + output_token_count: 1, + cached_token_count: 0, + }, + finish_reason: FinishReason::stop_eos(), + kv_transfer_params: None, + }), + ]); + + let events = structured_chat_event_stream(events, false) + .collect::>() + .await + .into_iter() + .collect::>>() + .unwrap(); + + assert!(matches!( + events[0], + ChatEvent::ToolCallStart { index: 0, .. } + )); + assert!(matches!( + events[1], + ChatEvent::ToolCallArgumentsDelta { index: 0, .. } + )); + assert!(matches!(events[2], ChatEvent::ToolCallEnd { index: 0, .. })); + let ChatEvent::Done { message, .. } = &events[3] else { + panic!("expected done"); + }; + let tool_calls = message.tool_calls().collect::>(); + assert_eq!(tool_calls.len(), 1); + assert_eq!(tool_calls[0].name, "first"); + } } diff --git a/rust/src/chat/src/parser/reasoning/mod.rs b/rust/src/chat/src/parser/reasoning/mod.rs index aa4d45964387..7de8a9d5fa12 100644 --- a/rust/src/chat/src/parser/reasoning/mod.rs +++ b/rust/src/chat/src/parser/reasoning/mod.rs @@ -5,9 +5,9 @@ use std::sync::LazyLock; pub use vllm_reasoning_parser::{ CohereCmdReasoningParser, DeepSeekR1ReasoningParser, DeepSeekV3ReasoningParser, DeepSeekV4ReasoningParser, Gemma4ReasoningParser, Glm45ReasoningParser, KimiK2ReasoningParser, - KimiReasoningParser, MiniMaxM2ReasoningParser, NemotronV3ReasoningParser, Qwen3ReasoningParser, - ReasoningDelta, ReasoningError, ReasoningParser, SeedOssReasoningParser, Step3ReasoningParser, - Step3p5ReasoningParser, + KimiReasoningParser, MiniMaxM2ReasoningParser, MiniMaxM3ReasoningParser, + NemotronV3ReasoningParser, Qwen3ReasoningParser, ReasoningDelta, ReasoningError, + ReasoningParser, SeedOssReasoningParser, Step3ReasoningParser, Step3p5ReasoningParser, }; use vllm_tokenizer::DynTokenizer; @@ -24,6 +24,7 @@ pub mod names { pub const KIMI: &str = "kimi"; pub const KIMI_K2: &str = "kimi_k2"; pub const MINIMAX_M2: &str = "minimax_m2"; + pub const MINIMAX_M3: &str = "minimax_m3"; pub const NEMOTRON_V3: &str = "nemotron_v3"; pub const QWEN3: &str = "qwen3"; pub const SEED_OSS: &str = "seed_oss"; @@ -62,6 +63,7 @@ impl ReasoningParserFactory { .register_parser::(names::KIMI) .register_parser::(names::KIMI_K2) .register_parser::(names::MINIMAX_M2) + .register_parser::(names::MINIMAX_M3) .register_parser::(names::NEMOTRON_V3) .register_parser::(names::QWEN3) .register_parser::(names::SEED_OSS) @@ -90,6 +92,8 @@ impl ReasoningParserFactory { .register_pattern("step3", names::STEP3) .register_pattern("seed-oss", names::SEED_OSS) .register_pattern("seedoss", names::SEED_OSS) + .register_pattern("minimax-m3", names::MINIMAX_M3) + .register_pattern("mm-m3", names::MINIMAX_M3) .register_pattern("minimax", names::MINIMAX_M2) .register_pattern("mm-m2", names::MINIMAX_M2) .register_pattern("cohere", names::COHERE_CMD) diff --git a/rust/src/chat/src/parser/reasoning/tests.rs b/rust/src/chat/src/parser/reasoning/tests.rs index 803926d16bad..58d987770c65 100644 --- a/rust/src/chat/src/parser/reasoning/tests.rs +++ b/rust/src/chat/src/parser/reasoning/tests.rs @@ -34,10 +34,12 @@ fn factory_contains_and_lists_registered_parsers() { assert!(factory.contains(names::DEEPSEEK_V4)); assert!(factory.contains(names::SEED_OSS)); assert!(factory.contains(names::STEP3P5)); + assert!(factory.contains(names::MINIMAX_M3)); assert!(factory.list().contains(&names::QWEN3.to_string())); assert!(factory.list().contains(&names::DEEPSEEK_V4.to_string())); assert!(factory.list().contains(&names::SEED_OSS.to_string())); assert!(factory.list().contains(&names::STEP3P5.to_string())); + assert!(factory.list().contains(&names::MINIMAX_M3.to_string())); } #[test] @@ -88,6 +90,19 @@ fn factory_routes_seed_oss_models() { ); } +#[test] +fn factory_resolves_minimax_m3_before_generic_minimax() { + let factory = ReasoningParserFactory::new(); + assert_eq!( + factory.resolve_name_for_model("MiniMaxAI/Minimax-M3-preview"), + Some(names::MINIMAX_M3) + ); + assert_eq!( + factory.resolve_name_for_model("mm-m3"), + Some(names::MINIMAX_M3) + ); +} + #[test] fn factory_rejects_unknown_parser_names() { let tokenizer = Arc::new(FakeTokenizer); diff --git a/rust/src/chat/src/parser/tool/mod.rs b/rust/src/chat/src/parser/tool/mod.rs index 29961d1d82a0..7561aa071ac8 100644 --- a/rust/src/chat/src/parser/tool/mod.rs +++ b/rust/src/chat/src/parser/tool/mod.rs @@ -4,10 +4,11 @@ use std::sync::LazyLock; pub use vllm_tool_parser::{ DeepSeekV3ToolParser, DeepSeekV4ToolParser, DeepSeekV31ToolParser, DeepSeekV32ToolParser, - Gemma4ToolParser, Glm45MoeToolParser, Glm47MoeToolParser, HermesToolParser, HyV3ToolParser, - Internlm2ToolParser, KimiK2ToolParser, Llama3JsonToolParser, MinimaxM2ToolParser, - MistralToolParser, Phi4MiniJsonToolParser, Qwen3CoderToolParser, Qwen3XmlToolParser, - ToolCallDelta, ToolParser, ToolParserError, ToolParserOutput, + Gemma4ToolParser, Glm45MoeToolParser, Glm47MoeToolParser, Granite4ToolParser, HermesToolParser, + HyV3ToolParser, Internlm2ToolParser, KimiK2ToolParser, Llama3JsonToolParser, + MinimaxM2ToolParser, MinimaxM3ToolParser, MistralToolParser, Phi4MiniJsonToolParser, + Qwen3CoderToolParser, Qwen3XmlToolParser, ToolCallDelta, ToolParser, ToolParserError, + ToolParserOutput, }; use crate::parser::ParserFactory; @@ -22,6 +23,7 @@ pub mod names { pub const GLM45: &str = "glm45"; pub const GLM47: &str = "glm47"; pub const GEMMA4: &str = "gemma4"; + pub const GRANITE4: &str = "granite4"; pub const HERMES: &str = "hermes"; pub const HY_V3: &str = "hy_v3"; // Matches the Python CLI name `--tool-call-parser internlm`, which Python @@ -31,6 +33,7 @@ pub mod names { pub const LLAMA3_JSON: &str = "llama3_json"; pub const LLAMA4_JSON: &str = "llama4_json"; pub const MINIMAX_M2: &str = "minimax_m2"; + pub const MINIMAX_M3: &str = "minimax_m3"; pub const MISTRAL: &str = "mistral"; pub const PHI4_MINI_JSON: &str = "phi4_mini_json"; pub const QWEN3_CODER: &str = "qwen3_coder"; @@ -64,6 +67,7 @@ impl ToolParserFactory { .register_parser::(names::GLM45) .register_parser::(names::GLM47) .register_parser::(names::GEMMA4) + .register_parser::(names::GRANITE4) .register_parser::(names::HERMES) .register_parser::(names::HY_V3) .register_parser::(names::INTERNLM) @@ -71,6 +75,7 @@ impl ToolParserFactory { .register_parser::(names::LLAMA3_JSON) .register_parser::(names::LLAMA4_JSON) .register_parser::(names::MINIMAX_M2) + .register_parser::(names::MINIMAX_M3) .register_parser::(names::MISTRAL) .register_parser::(names::PHI4_MINI_JSON) .register_parser::(names::QWEN3_XML) @@ -107,7 +112,10 @@ impl ToolParserFactory { .register_pattern("glm-4.5", names::GLM45) .register_pattern("gemma4", names::GEMMA4) .register_pattern("gemma-4", names::GEMMA4) + .register_pattern("granite-4", names::GRANITE4) .register_pattern("kimi-k2", names::KIMI_K2) + .register_pattern("minimax-m3", names::MINIMAX_M3) + .register_pattern("mm-m3", names::MINIMAX_M3) .register_pattern("minimax", names::MINIMAX_M2) .register_pattern("mm-m2", names::MINIMAX_M2); diff --git a/rust/src/chat/src/parser/tool/tests.rs b/rust/src/chat/src/parser/tool/tests.rs index 6fd380bd223d..c40500adc74a 100644 --- a/rust/src/chat/src/parser/tool/tests.rs +++ b/rust/src/chat/src/parser/tool/tests.rs @@ -145,6 +145,10 @@ fn factory_new_resolves_default_patterns() { factory.resolve_name_for_model("google/gemma-4-27b-it"), Some(names::GEMMA4) ); + assert_eq!( + factory.resolve_name_for_model("ibm-granite/granite-4.0-h-tiny"), + Some(names::GRANITE4) + ); assert_eq!( factory.resolve_name_for_model("NousResearch/Hermes-3-Llama-3.1-8B"), Some(names::HERMES) @@ -153,6 +157,14 @@ fn factory_new_resolves_default_patterns() { factory.resolve_name_for_model("tencent/Hy3-preview"), Some(names::HY_V3) ); + assert_eq!( + factory.resolve_name_for_model("MiniMax/MiniMax-M3-Text"), + Some(names::MINIMAX_M3) + ); + assert_eq!( + factory.resolve_name_for_model("org/mm-m3-base"), + Some(names::MINIMAX_M3) + ); assert_eq!( factory.resolve_name_for_model("MiniMax/MiniMax-M2-01"), Some(names::MINIMAX_M2) diff --git a/rust/src/chat/src/request.rs b/rust/src/chat/src/request.rs index 842c941a6c00..7b9ae5f663e0 100644 --- a/rust/src/chat/src/request.rs +++ b/rust/src/chat/src/request.rs @@ -406,6 +406,10 @@ pub struct ChatRequest { pub tools: Vec, /// Tool-choice behavior for this request. pub tool_choice: ChatToolChoice, + /// Whether the model may return more than one tool call per response. + /// + /// When `false`, only the first parsed tool call is surfaced northbound. + pub parallel_tool_calls: bool, /// Text decode options for incremental detokenization. pub decode_options: TextDecodeOptions, /// Whether to emit intermediate northbound content deltas before the @@ -442,6 +446,7 @@ impl ChatRequest { chat_options: ChatOptions::default(), tools: Vec::new(), tool_choice: ChatToolChoice::None, + parallel_tool_calls: true, decode_options: TextDecodeOptions::default(), intermediate: true, priority: 0, diff --git a/rust/src/cmd/src/cli.rs b/rust/src/cmd/src/cli.rs index 12a85421bd35..003d96fa92be 100644 --- a/rust/src/cmd/src/cli.rs +++ b/rust/src/cmd/src/cli.rs @@ -23,8 +23,8 @@ use vllm_engine_core_client::TransportMode; use vllm_managed_engine::ManagedEngineConfig; use vllm_managed_engine::cli::{ManagedEngineArgs, repartition_managed_engine_args}; use vllm_server::{ - ApiServerOptions, ChatTemplateContentFormatOption, Config, CoordinatorMode, HttpListenerMode, - ParserSelection, RendererSelection, + ApiServerOptions, ChatTemplateContentFormatOption, Config, CoordinatorMode, CorsConfig, + HttpListenerMode, ParserSelection, RendererSelection, }; use crate::cli::unsupported::UnsupportedArgs; @@ -84,6 +84,13 @@ pub enum Command { Serve(ServeArgs), } +/// A JSON-encoded list of strings, matching Python's `json.loads` CLI type for +/// the CORS list arguments (e.g. `--allowed-origins '["*"]'`). Parsing the whole +/// value as one item keeps clap from treating the field as a repeated flag. +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(transparent)] +pub struct JsonStringList(pub Vec); + /// Runtime arguments shared by the external-engine and managed-engine paths. #[serde_as] #[derive(Educe, Clone, Args, PartialEq, Eq, Deserialize)] @@ -127,6 +134,11 @@ pub struct SharedRuntimeArgs { /// `config.json`. #[arg(long)] pub max_model_len: Option, + /// Maximum number of log probabilities to return when `logprobs` is + /// specified in sampling parameters. `-1` means no cap. + #[arg(long, value_parser = clap::value_parser!(i32).range(-1..), allow_negative_numbers = true)] + #[serde(default)] + pub max_logprobs: Option, /// TCP port for the gRPC Generate service. When not set, no gRPC server is /// started. #[arg(long)] @@ -215,6 +227,30 @@ pub struct SharedRuntimeArgs { #[serde(default)] pub served_model_name: Vec, + /// CORS allowed origins as a JSON list. `["*"]` allows any origin. + #[arg(long, value_parser = parse_json::, value_name = "JSON", default_value = r#"["*"]"#)] + #[serde(default = "default_cors_wildcard")] + pub allowed_origins: JsonStringList, + + /// CORS allowed methods as a JSON list. `["*"]` allows the standard set. + #[arg(long, value_parser = parse_json::, value_name = "JSON", default_value = r#"["*"]"#)] + #[serde(default = "default_cors_wildcard")] + pub allowed_methods: JsonStringList, + + /// CORS allowed request headers as a JSON list. `["*"]` mirrors the request. + #[arg(long, value_parser = parse_json::, value_name = "JSON", default_value = r#"["*"]"#)] + #[serde(default = "default_cors_wildcard")] + pub allowed_headers: JsonStringList, + + /// Allow CORS credentials (cookies, authorization headers). + #[arg( + long, + default_missing_value = "true", + num_args = 0..=1 + )] + #[serde(default)] + pub allow_credentials: bool, + /// Unsupported Python vLLM frontend arguments recognized but not yet /// implemented in Rust. #[educe(Debug(ignore))] @@ -254,16 +290,19 @@ impl SharedRuntimeArgs { input_address: String, output_address: String, coordinator_address: Option, + engine_start_index: u32, engine_count: usize, ) -> Config { let ready_timeout = self.ready_timeout(); let shutdown_timeout = self.shutdown_timeout(); let api_server_options = self.api_server_options(); + let cors = self.cors_config(); Config { transport_mode: TransportMode::Bootstrapped { input_address, output_address, + engine_start_index, engine_count, ready_timeout, }, @@ -281,7 +320,9 @@ impl SharedRuntimeArgs { chat_template: self.chat_template, default_chat_template_kwargs: self.default_chat_template_kwargs, chat_template_content_format: self.chat_template_content_format, + max_logprobs: self.max_logprobs, api_server_options, + cors, api_keys: self.api_key, disable_log_stats: self.disable_log_stats, grpc_port: self.grpc_port, @@ -303,6 +344,7 @@ impl SharedRuntimeArgs { let ready_timeout = self.ready_timeout(); let shutdown_timeout = self.shutdown_timeout(); let api_server_options = self.api_server_options(); + let cors = self.cors_config(); Config { transport_mode: TransportMode::HandshakeOwner { @@ -324,7 +366,9 @@ impl SharedRuntimeArgs { chat_template: self.chat_template, default_chat_template_kwargs: self.default_chat_template_kwargs, chat_template_content_format: self.chat_template_content_format, + max_logprobs: self.max_logprobs, api_server_options, + cors, api_keys: self.api_key, disable_log_stats: self.disable_log_stats, grpc_port: self.grpc_port, @@ -339,12 +383,25 @@ impl SharedRuntimeArgs { enable_request_id_headers: self.enable_request_id_headers, } } + + fn cors_config(&self) -> CorsConfig { + CorsConfig { + allow_origins: self.allowed_origins.0.clone(), + allow_methods: self.allowed_methods.0.clone(), + allow_headers: self.allowed_headers.0.clone(), + allow_credentials: self.allow_credentials, + } + } } fn default_engine_ready_timeout_secs() -> u64 { 600 } +fn default_cors_wildcard() -> JsonStringList { + JsonStringList(vec!["*".to_string()]) +} + fn parse_json(value: &str) -> Result { serde_json::from_str(value).map_err(|e| format!("invalid JSON object: {}", e.as_report())) } @@ -380,6 +437,10 @@ pub struct FrontendArgs { /// `stats_update_address`. #[arg(long)] pub coordinator_address: Option, + /// First data-parallel engine rank expected to register with this + /// bootstrapped frontend. + #[arg(long, default_value_t = 0)] + pub engine_start_index: u32, /// Total number of data-parallel engines expected for this frontend. #[arg(long, default_value_t = 1)] pub engine_count: usize, @@ -397,6 +458,7 @@ impl FrontendArgs { self.input_address, self.output_address, self.coordinator_address, + self.engine_start_index, self.engine_count, ) } @@ -467,7 +529,10 @@ impl ServeArgs { self.managed_engine.clone().into_config( self.runtime.model.clone(), self.runtime.max_model_len, + self.runtime.max_logprobs, self.runtime.language_model_only, + self.runtime.disable_log_stats, + self.runtime.shutdown_timeout, handshake_port, ) } diff --git a/rust/src/cmd/src/cli/tests.rs b/rust/src/cmd/src/cli/tests.rs index e351e7e1c8db..c57c23e017c3 100644 --- a/rust/src/cmd/src/cli/tests.rs +++ b/rust/src/cmd/src/cli/tests.rs @@ -38,6 +38,7 @@ fn serve_args_forward_python_flags_with_separator() { max_model_len: Some( 512, ), + max_logprobs: None, grpc_port: None, shutdown_timeout: 0, chat_template: None, @@ -48,6 +49,22 @@ fn serve_args_forward_python_flags_with_separator() { enable_request_id_headers: false, disable_log_stats: false, served_model_name: [], + allowed_origins: JsonStringList( + [ + "*", + ], + ), + allowed_methods: JsonStringList( + [ + "*", + ], + ), + allowed_headers: JsonStringList( + [ + "*", + ], + ), + allow_credentials: false, }, managed_engine: ManagedEngineArgs { python: "../vllm/.venv/bin/python", @@ -100,6 +117,63 @@ fn serve_args_auto_forward_enable_lora_to_python() { assert_eq!(args.managed_engine.python_args, vec!["--enable-lora"]); } +#[test] +fn serve_args_forward_shutdown_timeout_to_managed_engine() { + let cli = Cli::try_parse_from([ + "vllm-rs", + "serve", + "Qwen/Qwen3-0.6B", + "--shutdown-timeout", + "60", + ]) + .unwrap(); + + let Command::Serve(args) = cli.command else { + panic!("expected serve args"); + }; + assert_eq!(args.runtime.shutdown_timeout, 60); + + let config = args.to_managed_engine_config(5555); + assert_eq!(config.python_args, vec!["--shutdown-timeout", "60"]); +} + +#[test] +fn serve_args_forward_disable_log_stats_to_managed_engine() { + let cli = Cli::try_parse_from(["vllm-rs", "serve", "Qwen/Qwen3-0.6B", "--disable-log-stats"]) + .unwrap(); + + let Command::Serve(args) = cli.command else { + panic!("expected serve args"); + }; + assert!(args.runtime.disable_log_stats); + + let config = args.to_managed_engine_config(5555); + assert_eq!(config.python_args, vec!["--disable-log-stats"]); +} + +#[test] +fn serve_args_forward_max_logprobs_to_frontend_and_managed_engine() { + let cli = Cli::try_parse_from([ + "vllm-rs", + "serve", + "Qwen/Qwen3-0.6B", + "--max-logprobs", + "-1", + ]) + .unwrap(); + + let Command::Serve(args) = cli.command else { + panic!("expected serve args"); + }; + assert_eq!(args.runtime.max_logprobs, Some(-1)); + + let frontend_config = args.to_frontend_config("tcp://127.0.0.1:62100".to_string()); + assert_eq!(frontend_config.max_logprobs, Some(-1)); + + let engine_config = args.to_managed_engine_config(5555); + assert_eq!(engine_config.python_args, vec!["--max-logprobs", "-1"]); +} + #[test] fn serve_args_auto_forward_python_multi_char_alias_without_separator() { let cli = Cli::try_parse_from(["vllm-rs", "serve", "Qwen/Qwen3-0.6B", "-tp", "2"]).unwrap(); @@ -278,11 +352,17 @@ fn serve_args_reject_unknown_renderer_value() { #[test] fn serve_args_reject_unsupported_flag_arg() { - let error = Cli::try_parse_from(["vllm-rs", "serve", "Qwen/Qwen3-0.6B", "--allow-credentials"]) - .unwrap_err(); + let error = Cli::try_parse_from([ + "vllm-rs", + "serve", + "Qwen/Qwen3-0.6B", + "--ssl-keyfile", + "/tmp/key.pem", + ]) + .unwrap_err(); expect![[r#" - error: invalid value 'true' for '--allow-credentials []': argument is not implemented in Rust frontend yet + error: invalid value '/tmp/key.pem' for '--ssl-keyfile ': argument is not implemented in Rust frontend yet Remove this unsupported argument to continue. @@ -290,8 +370,7 @@ fn serve_args_reject_unsupported_flag_arg() { This may lead to unexpected behavior as the Rust frontend will completely ignore that argument. For more information, try '--help'. - "#]] - .assert_eq(&error.to_string()); + "#]].assert_eq(&error.to_string()); } #[test] @@ -345,6 +424,7 @@ fn frontend_args_accept_json() { coordinator_address: Some( "tcp://127.0.0.1:7000", ), + engine_start_index: 0, engine_count: 1, runtime: SharedRuntimeArgs { model: "Qwen/Qwen3-0.6B", @@ -354,6 +434,7 @@ fn frontend_args_accept_json() { renderer: Auto, language_model_only: false, max_model_len: None, + max_logprobs: None, grpc_port: None, shutdown_timeout: 0, chat_template: None, @@ -364,6 +445,22 @@ fn frontend_args_accept_json() { enable_request_id_headers: false, disable_log_stats: false, served_model_name: [], + allowed_origins: JsonStringList( + [ + "*", + ], + ), + allowed_methods: JsonStringList( + [ + "*", + ], + ), + allowed_headers: JsonStringList( + [ + "*", + ], + ), + allow_credentials: false, }, }, ), @@ -397,6 +494,7 @@ fn frontend_args_json_applies_defaults() { assert_eq!(args.runtime.reasoning_parser, ParserSelection::Auto); assert_eq!(args.runtime.renderer, RendererSelection::Auto); assert_eq!(args.runtime.max_model_len, None); + assert_eq!(args.runtime.max_logprobs, None); assert_eq!(args.runtime.shutdown_timeout, 0); } @@ -412,7 +510,7 @@ fn frontend_args_json_accepts_supported_non_default_fields() { "--output-address", "ipc:///tmp/output.sock", "--args-json", - r#"{"model_tag":"Qwen/Qwen3-0.6B","engine_ready_timeout_secs":42,"tool_call_parser":"hermes","reasoning_parser":"qwen3_thinking","tokenizer_mode":"deepseek_v32","language_model_only":true,"max_model_len":8192,"shutdown_timeout":3}"#, + r#"{"model_tag":"Qwen/Qwen3-0.6B","engine_ready_timeout_secs":42,"tool_call_parser":"hermes","reasoning_parser":"qwen3_thinking","tokenizer_mode":"deepseek_v32","language_model_only":true,"max_model_len":8192,"max_logprobs":-1,"shutdown_timeout":3}"#, ]) .unwrap(); @@ -431,6 +529,7 @@ fn frontend_args_json_accepts_supported_non_default_fields() { assert_eq!(args.runtime.renderer, RendererSelection::DeepSeekV32); assert!(args.runtime.language_model_only); assert_eq!(args.runtime.max_model_len, Some(8192)); + assert_eq!(args.runtime.max_logprobs, Some(-1)); assert_eq!(args.runtime.shutdown_timeout, 3); } @@ -497,6 +596,71 @@ fn frontend_args_json_sets_prompt_tokens_details_flag() { assert!(args.runtime.enable_prompt_tokens_details); } +#[test] +fn serve_args_parse_cors_flags() { + let cli = Cli::try_parse_from([ + "vllm-rs", + "serve", + "Qwen/Qwen3-0.6B", + "--allowed-origins", + r#"["http://a.com","http://b.com"]"#, + "--allowed-methods", + r#"["GET","POST"]"#, + "--allow-credentials", + ]) + .unwrap(); + + let Command::Serve(serve) = cli.command else { + panic!("expected serve args"); + }; + assert_eq!( + serve.runtime.allowed_origins.0, + ["http://a.com", "http://b.com"] + ); + assert_eq!(serve.runtime.allowed_methods.0, ["GET", "POST"]); + assert!(serve.runtime.allow_credentials); + // Unspecified lists keep the permissive default. + assert_eq!(serve.runtime.allowed_headers.0, ["*"]); +} + +#[test] +fn serve_args_cors_defaults_are_permissive() { + let cli = Cli::try_parse_from(["vllm-rs", "serve", "Qwen/Qwen3-0.6B"]).unwrap(); + + let Command::Serve(serve) = cli.command else { + panic!("expected serve args"); + }; + assert_eq!(serve.runtime.allowed_origins.0, ["*"]); + assert_eq!(serve.runtime.allowed_methods.0, ["*"]); + assert_eq!(serve.runtime.allowed_headers.0, ["*"]); + assert!(!serve.runtime.allow_credentials); +} + +#[test] +fn frontend_args_json_parses_cors_fields() { + let cli = Cli::try_parse_from([ + "vllm-rs", + "frontend", + "--listen-fd", + "3", + "--input-address", + "ipc:///tmp/input.sock", + "--output-address", + "ipc:///tmp/output.sock", + "--args-json", + r#"{"model_tag":"Qwen/Qwen3-0.6B","allowed_origins":["http://a.com"],"allow_credentials":true}"#, + ]) + .unwrap(); + + let Command::Frontend(args) = cli.command else { + panic!("expected frontend args"); + }; + assert_eq!(args.runtime.allowed_origins.0, ["http://a.com"]); + assert!(args.runtime.allow_credentials); + // Unspecified lists fall back to the permissive default via serde. + assert_eq!(args.runtime.allowed_methods.0, ["*"]); +} + #[test] fn frontend_args_json_rejects_unsupported_fields() { let error = Cli::try_parse_from([ @@ -509,14 +673,14 @@ fn frontend_args_json_rejects_unsupported_fields() { "--output-address", "ipc:///tmp/output.sock", "--args-json", - r#"{"model_tag":"Qwen/Qwen3-0.6B","allow_credentials":true}"#, + r#"{"model_tag":"Qwen/Qwen3-0.6B","ssl_keyfile":"/tmp/key.pem"}"#, ]) .unwrap_err(); expect![[r#" - error: invalid value '{"model_tag":"Qwen/Qwen3-0.6B","allow_credentials":true}' for '--args-json ': + error: invalid value '{"model_tag":"Qwen/Qwen3-0.6B","ssl_keyfile":"/tmp/key.pem"}' for '--args-json ': The following arguments are not implemented in Rust frontend yet: - - allow_credentials + - ssl_keyfile Remove these arguments to continue. @@ -536,15 +700,15 @@ fn frontend_args_json_aggregates_multiple_unsupported_fields() { "--output-address", "ipc:///tmp/output.sock", "--args-json", - r#"{"model_tag":"Qwen/Qwen3-0.6B","allow_credentials":true,"ssl_keyfile":"/tmp/key.pem"}"#, + r#"{"model_tag":"Qwen/Qwen3-0.6B","response_role":"assistant","ssl_keyfile":"/tmp/key.pem"}"#, ]) .unwrap_err(); let actual = error.to_string().replace(": \n", ":\n"); expect![[r#" - error: invalid value '{"model_tag":"Qwen/Qwen3-0.6B","allow_credentials":true,"ssl_keyfile":"/tmp/key.pem"}' for '--args-json ': + error: invalid value '{"model_tag":"Qwen/Qwen3-0.6B","response_role":"assistant","ssl_keyfile":"/tmp/key.pem"}' for '--args-json ': The following arguments are not implemented in Rust frontend yet: - - allow_credentials + - response_role - ssl_keyfile Remove these arguments to continue. @@ -758,6 +922,7 @@ fn serve_args_accept_handshake_aliases() { renderer: Auto, language_model_only: false, max_model_len: None, + max_logprobs: None, grpc_port: None, shutdown_timeout: 0, chat_template: None, @@ -768,6 +933,22 @@ fn serve_args_accept_handshake_aliases() { enable_request_id_headers: false, disable_log_stats: false, served_model_name: [], + allowed_origins: JsonStringList( + [ + "*", + ], + ), + allowed_methods: JsonStringList( + [ + "*", + ], + ), + allowed_headers: JsonStringList( + [ + "*", + ], + ), + allow_credentials: false, }, managed_engine: ManagedEngineArgs { python: "python3", @@ -883,11 +1064,24 @@ fn serve_frontend_config_uses_dp_address_as_advertised_host() { chat_template: None, default_chat_template_kwargs: None, chat_template_content_format: Auto, + max_logprobs: None, api_server_options: ApiServerOptions { enable_log_requests: false, enable_prompt_tokens_details: false, enable_request_id_headers: false, }, + cors: CorsConfig { + allow_origins: [ + "*", + ], + allow_methods: [ + "*", + ], + allow_headers: [ + "*", + ], + allow_credentials: false, + }, api_keys: [], disable_log_stats: false, grpc_port: None, @@ -951,11 +1145,24 @@ fn serve_frontend_config_keeps_tcp_transport_for_non_local_only_topology() { chat_template: None, default_chat_template_kwargs: None, chat_template_content_format: Auto, + max_logprobs: None, api_server_options: ApiServerOptions { enable_log_requests: false, enable_prompt_tokens_details: false, enable_request_id_headers: false, }, + cors: CorsConfig { + allow_origins: [ + "*", + ], + allow_methods: [ + "*", + ], + allow_headers: [ + "*", + ], + allow_credentials: false, + }, api_keys: [], disable_log_stats: false, grpc_port: None, @@ -999,8 +1206,10 @@ fn frontend_config_uses_external_coordinator_when_coordinator_address_is_present "ipc:///tmp/output.sock", "--coordinator-address", "tcp://127.0.0.1:7000", + "--engine-start-index", + "3", "--engine-count", - "2", + "1", "--args-json", r#"{"model_tag":"Qwen/Qwen3-0.6B"}"#, ]) @@ -1016,7 +1225,8 @@ fn frontend_config_uses_external_coordinator_when_coordinator_address_is_present transport_mode: Bootstrapped { input_address: "ipc:///tmp/input.sock", output_address: "ipc:///tmp/output.sock", - engine_count: 2, + engine_start_index: 3, + engine_count: 1, ready_timeout: 600s, }, coordinator_mode: External { @@ -1034,11 +1244,24 @@ fn frontend_config_uses_external_coordinator_when_coordinator_address_is_present chat_template: None, default_chat_template_kwargs: None, chat_template_content_format: Auto, + max_logprobs: None, api_server_options: ApiServerOptions { enable_log_requests: false, enable_prompt_tokens_details: false, enable_request_id_headers: false, }, + cors: CorsConfig { + allow_origins: [ + "*", + ], + allow_methods: [ + "*", + ], + allow_headers: [ + "*", + ], + allow_credentials: false, + }, api_keys: [], disable_log_stats: false, grpc_port: None, diff --git a/rust/src/cmd/src/cli/unsupported.rs b/rust/src/cmd/src/cli/unsupported.rs index e9dd5285e5e2..e7fb4bc0ba7f 100644 --- a/rust/src/cmd/src/cli/unsupported.rs +++ b/rust/src/cmd/src/cli/unsupported.rs @@ -202,14 +202,6 @@ pub struct EngineUnsupportedArgs { #[arg(long)] pub tokenizer_revision: Option, - /// Maximum number of log probabilities to return when `logprobs` is - /// specified in `SamplingParams`. The default value comes the default for - /// the OpenAI Chat Completions API. -1 means no cap, i.e. all - /// (output_length * vocab_size) logprobs are allowed to be returned and - /// it may cause OOM. - #[arg(long)] - pub max_logprobs: Option, - /// Skip initialization of tokenizer and detokenizer. Expects valid /// `prompt_token_ids` and `None` for prompt from the input. The generated /// output will contain token ids. @@ -534,27 +526,6 @@ pub struct ServerUnsupportedArgs { #[arg(long)] pub disable_access_log_for_endpoints: Option, - /// Allow credentials. - #[arg( - long, - visible_alias = "no-allow-credentials", - default_missing_value = "true", - num_args = 0..=1 - )] - pub allow_credentials: Option, - - /// Allowed origins. - #[arg(long)] - pub allowed_origins: Option, - - /// Allowed methods. - #[arg(long)] - pub allowed_methods: Option, - - /// Allowed headers. - #[arg(long)] - pub allowed_headers: Option, - /// The file path to the SSL key file. #[arg(long)] pub ssl_keyfile: Option, diff --git a/rust/src/engine-core-client/src/client.rs b/rust/src/engine-core-client/src/client.rs index 73ebe9ef4072..b4357f77c7cf 100644 --- a/rust/src/engine-core-client/src/client.rs +++ b/rust/src/engine-core-client/src/client.rs @@ -56,6 +56,9 @@ pub enum TransportMode { /// Output PULL socket address that engines will connect to for /// responses. output_address: String, + /// First data-parallel engine rank expected to register on this + /// transport. + engine_start_index: u32, /// Total number of engines expected to register on this transport. engine_count: usize, /// Maximum time to wait for all expected engines to register. @@ -246,6 +249,7 @@ impl EngineCoreClient { TransportMode::Bootstrapped { input_address, output_address, + engine_start_index, engine_count, ready_timeout, } => { @@ -256,6 +260,7 @@ impl EngineCoreClient { transport::connect_bootstrapped( input_address, output_address, + *engine_start_index, *engine_count, *ready_timeout, ) @@ -490,6 +495,10 @@ impl EngineCoreClient { return Ok(()); } + // Finalize the consumer streams first, before the engine round-trip. + let all_request_ids: Vec = abortable.values().flatten().cloned().collect(); + self.inner.abort_requests_locally(&all_request_ids); + for (engine_id, request_ids) in abortable { self.inner.do_abort_requests(&engine_id, &request_ids).await?; } diff --git a/rust/src/engine-core-client/src/client/imp.rs b/rust/src/engine-core-client/src/client/imp.rs index 6f218717ed78..1107e415d3ea 100644 --- a/rust/src/engine-core-client/src/client/imp.rs +++ b/rust/src/engine-core-client/src/client/imp.rs @@ -1,5 +1,6 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; use arc_swap::ArcSwapOption; use parking_lot::Mutex; @@ -126,6 +127,20 @@ impl ClientInner { self.request_reg.lock().finish_many(request_ids) } + /// Finalize client-initiated aborts by pushing a terminal `Abort` output + /// down each request's stream and removing it from the registry. Returns + /// the request ids that were still active. See [`RequestRegistry::abort_many`]. + pub fn abort_requests_locally<'a>( + &self, + request_ids: impl IntoIterator, + ) -> Vec { + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs_f64()) + .unwrap_or(0.0); + self.request_reg.lock().abort_many(request_ids, timestamp) + } + /// Apply one scheduler stats update for the given engine to the local /// routing state. Returns `false` if the engine is unknown to the /// client. diff --git a/rust/src/engine-core-client/src/client/state.rs b/rust/src/engine-core-client/src/client/state.rs index 062f284d90dc..51da1c10f6b3 100644 --- a/rust/src/engine-core-client/src/client/state.rs +++ b/rust/src/engine-core-client/src/client/state.rs @@ -9,7 +9,7 @@ use crate::client::stream::EngineCoreStreamOutput; use crate::error::{Error, Result}; use crate::protocol::stats::SchedulerStats; use crate::protocol::utility::UtilityOutput; -use crate::protocol::{EngineCoreEventType, EngineCoreOutput}; +use crate::protocol::{EngineCoreEventType, EngineCoreFinishReason, EngineCoreOutput}; use crate::transport::ConnectedEngine; pub type OutputSender = mpsc::UnboundedSender>; @@ -289,6 +289,34 @@ impl RequestRegistry { .collect() } + /// Finalize client-initiated aborts: remove each request and push a + /// terminal output with `finish_reason = Abort` down its stream before the + /// sender drops. Returns the request ids that were still active. + pub fn abort_many<'a>( + &mut self, + request_ids: impl IntoIterator, + timestamp: f64, + ) -> Vec { + let mut aborted = Vec::new(); + for request_id in request_ids { + let Some((sender, engine_id)) = self.remove(request_id) else { + continue; + }; + let output = EngineCoreStreamOutput { + engine_index: engine_id.engine_index().unwrap_or(0), + timestamp, + output: EngineCoreOutput { + request_id: request_id.clone(), + finish_reason: Some(EngineCoreFinishReason::Abort), + ..EngineCoreOutput::default() + }, + }; + let _ = sender.send(Ok(output)); + aborted.push(request_id.clone()); + } + aborted + } + /// Remove one request from the local registry. Returns the tracked entry if /// it exists. #[must_use] diff --git a/rust/src/engine-core-client/src/mock_engine.rs b/rust/src/engine-core-client/src/mock_engine.rs index 32cd48c396f5..11c012b1f163 100644 --- a/rust/src/engine-core-client/src/mock_engine.rs +++ b/rust/src/engine-core-client/src/mock_engine.rs @@ -15,6 +15,8 @@ use crate::protocol::{ModelDtype, decode_msgpack, encode_msgpack}; pub const DEFAULT_MOCK_MAX_MODEL_LEN: u64 = 1024 * 1024; /// Default KV block count advertised by reusable mock engine helpers. pub const DEFAULT_MOCK_NUM_GPU_BLOCKS: u64 = 0; +/// Default KV block size (tokens per block) +pub const DEFAULT_MOCK_BLOCK_SIZE: u64 = 16; /// Startup behavior for one mock engine joining a frontend. #[derive(Debug, Clone)] @@ -46,9 +48,12 @@ pub fn default_ready_response() -> EngineCoreReadyResponse { EngineCoreReadyResponse { max_model_len: DEFAULT_MOCK_MAX_MODEL_LEN, num_gpu_blocks: DEFAULT_MOCK_NUM_GPU_BLOCKS, + block_size: DEFAULT_MOCK_BLOCK_SIZE, dp_stats_address: None, dtype: ModelDtype::Float32, vllm_version: "test-vllm-version".to_string(), + kv_cache_size_tokens: None, + kv_cache_max_concurrency: None, } } diff --git a/rust/src/engine-core-client/src/protocol/handshake.rs b/rust/src/engine-core-client/src/protocol/handshake.rs index d659dc8a2446..3ca8774b2d6c 100644 --- a/rust/src/engine-core-client/src/protocol/handshake.rs +++ b/rust/src/engine-core-client/src/protocol/handshake.rs @@ -28,7 +28,7 @@ pub struct ReadyMessage { /// profiling). /// /// Original Python definition: -/// +/// #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EngineCoreReadyResponse { /// Engine-reported maximum model context length (auto-fitted after @@ -36,12 +36,18 @@ pub struct EngineCoreReadyResponse { pub max_model_len: u64, /// Number of GPU blocks available for KV cache on this engine. pub num_gpu_blocks: u64, + /// KV cache block size (tokens per block). + pub block_size: u64, /// DP coordinator stats publish address, if applicable. pub dp_stats_address: Option, /// Effective model dtype after Python vLLM resolves `--dtype`. pub dtype: ModelDtype, /// Python vLLM version reported by the engine process. pub vllm_version: String, + /// Total KV cache capacity in tokens, if reported. + pub kv_cache_size_tokens: Option, + /// Maximum achievable request concurrency given the KV cache, if reported. + pub kv_cache_max_concurrency: Option, } /// Frontend-owned ZMQ addresses that are sent to the engine during startup diff --git a/rust/src/engine-core-client/src/protocol/mod.rs b/rust/src/engine-core-client/src/protocol/mod.rs index 6fae982d2ea6..5e340b911766 100644 --- a/rust/src/engine-core-client/src/protocol/mod.rs +++ b/rust/src/engine-core-client/src/protocol/mod.rs @@ -44,6 +44,14 @@ fn default_repetition_penalty() -> f32 { 1.0 } +fn default_temperature() -> f32 { + 1.0 +} + +fn default_max_tokens() -> u32 { + 16 +} + mod classified_outputs; pub mod dtype; pub mod handshake; @@ -246,24 +254,28 @@ pub struct StructuredOutputsParams { /// /// Original Python definition: /// +// Python's SamplingParams is `omit_defaults=True`, so msgpack drops +// default-valued keys; default the whole struct. Per-field fns cover the +// non-zero defaults. #[serde_with::skip_serializing_none] -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, DefaultFromSerde)] +#[serde(default)] pub struct EngineCoreSamplingParams { /// Controls randomness. Lower values are more deterministic; zero means /// greedy sampling. + #[serde(default = "default_temperature")] pub temperature: f32, /// Cumulative probability threshold for nucleus sampling. #[serde(default = "default_top_p")] pub top_p: f32, /// Maximum number of top tokens to consider. `0` means all tokens. - #[serde(default)] pub top_k: u32, /// Random seed used by the sampler when present. pub seed: Option, /// Maximum number of tokens to generate per output sequence. + #[serde(default = "default_max_tokens")] pub max_tokens: u32, /// Minimum number of tokens to generate before EOS or stop-token handling. - #[serde(default)] pub min_tokens: u32, /// Number of log probabilities to return per generated token. /// @@ -274,7 +286,6 @@ pub struct EngineCoreSamplingParams { /// `None` disables prompt logprobs. `-1` requests the full vocabulary. pub prompt_logprobs: Option, /// Minimum probability threshold for token sampling. - #[serde(default)] pub min_p: f32, /// Frequency penalty applied by the sampler. pub frequency_penalty: f32, @@ -301,16 +312,13 @@ pub struct EngineCoreSamplingParams { pub all_stop_token_ids: BTreeSet, /// Logit biases to apply during sampling. /// Keys are token IDs - #[serde(default)] pub logit_bias: Option>, /// Restrict output to these token IDs only. - #[serde(default)] pub allowed_token_ids: Option>, /// Tokenized bad words to avoid during generation. - #[serde(default, rename = "_bad_words_token_ids")] + #[serde(rename = "_bad_words_token_ids")] pub bad_words_token_ids: Option>>, /// Parameters for configuring structured outputs (guided decoding). - #[serde(default)] pub structured_outputs: Option, /// Specific token IDs for which log probabilities should be returned at /// each position. @@ -318,15 +326,12 @@ pub struct EngineCoreSamplingParams { /// When set, the engine returns logprobs for exactly these tokens in /// addition to the sampled/scored token. Mutually exclusive with the /// `logprobs` count field in practice. - #[serde(default)] pub logprob_token_ids: Option>, /// If `Some(true)`, the request will not attempt to read from the prefix /// cache; newly computed blocks may still populate the cache. `None` /// defers to engine-core defaults. - #[serde(default)] pub skip_reading_prefix_cache: Option, /// Additional request parameters for custom extensions (from `vllm_xargs`). - #[serde(default)] pub extra_args: Option>, } @@ -640,4 +645,58 @@ mod tests { let value = serde_json::to_value(params).unwrap(); assert_eq!(value["_backend"], "guidance"); } + + /// A real `sampling_params` is a sparse `omit_defaults` map; absent fields + /// must fall back to defaults. `python_compat` can't catch this since Rust + /// encodes full maps (see `engine_core_request_serializes_as_full_array`). + #[test] + fn decodes_sampling_params_with_omitted_defaults() { + let sampling_params = Value::Map(vec![ + ( + Value::from("stop_token_ids"), + Value::Array(vec![Value::from(151643u32)]), + ), + (Value::from("skip_reading_prefix_cache"), Value::from(false)), + ]); + let request = Value::Array(vec![ + Value::from("req-omit-defaults"), + Value::Array(vec![ + Value::from(1u32), + Value::from(2u32), + Value::from(3u32), + ]), + Value::Nil, + sampling_params, + Value::Nil, + Value::from(1.0f64), + ]); + + let mut bytes = Vec::new(); + rmpv::encode::write_value(&mut bytes, &request).unwrap(); + + let decoded: EngineCoreRequest = decode_msgpack(&bytes) + .expect("a real omit_defaults request must decode (regression: missing field)"); + + assert_eq!(decoded.request_id, "req-omit-defaults"); + let sampling = decoded.sampling_params.expect("sampling params present"); + + assert_eq!(sampling.stop_token_ids, vec![151643]); + assert_eq!(sampling.skip_reading_prefix_cache, Some(false)); + + // Omitted fields -> Python defaults. + assert_eq!(sampling.temperature, 1.0); + assert_eq!(sampling.top_p, 1.0); + assert_eq!(sampling.top_k, 0); + assert_eq!(sampling.seed, None); + assert_eq!(sampling.max_tokens, 16); + assert_eq!(sampling.min_tokens, 0); + assert_eq!(sampling.min_p, 0.0); + assert_eq!(sampling.frequency_penalty, 0.0); + assert_eq!(sampling.presence_penalty, 0.0); + assert_eq!(sampling.repetition_penalty, 1.0); + assert_eq!(sampling.logprobs, None); + assert_eq!(sampling.prompt_logprobs, None); + assert_eq!(sampling.eos_token_id, None); + assert!(sampling.all_stop_token_ids.is_empty()); + } } diff --git a/rust/src/engine-core-client/src/tests/client.rs b/rust/src/engine-core-client/src/tests/client.rs index 32530d6d3855..c00a42268547 100644 --- a/rust/src/engine-core-client/src/tests/client.rs +++ b/rust/src/engine-core-client/src/tests/client.rs @@ -303,6 +303,7 @@ fn bootstrapped_test_config( transport_mode: TransportMode::Bootstrapped { input_address, output_address, + engine_start_index: 0, engine_count, ready_timeout, }, @@ -312,6 +313,34 @@ fn bootstrapped_test_config( } } +fn bootstrapped_test_config_with_start_index( + input_address: String, + output_address: String, + engine_start_index: u32, + engine_count: usize, + ready_timeout: Duration, + client_index: u32, + coordinator_mode: Option, +) -> EngineCoreClientConfig { + let mut config = bootstrapped_test_config( + input_address, + output_address, + engine_count, + ready_timeout, + client_index, + coordinator_mode, + ); + let TransportMode::Bootstrapped { + engine_start_index: start, + .. + } = &mut config.transport_mode + else { + unreachable!("bootstrapped_test_config returns bootstrapped transport") + }; + *start = engine_start_index; + config +} + async fn recv_xpub_message(xpub: &mut XPubSocket) -> Vec { xpub.recv().await.unwrap().into_vec() } @@ -1939,7 +1968,7 @@ async fn multi_engine_abort_is_grouped_and_utility_fans_out_to_all_engines() { let (shutdown_tx_0, engine_task_0) = spawn_mock_engine_task( handshake_address.clone(), - b"engine-0".to_vec(), + EngineId::from_engine_index(0).into_frame().to_vec(), |dealer, push| { Box::pin(async move { let utility = recv_engine_message(dealer).await; @@ -1993,7 +2022,7 @@ async fn multi_engine_abort_is_grouped_and_utility_fans_out_to_all_engines() { tokio::time::sleep(Duration::from_millis(50)).await; let (shutdown_tx_1, engine_task_1) = spawn_mock_engine_task( handshake_address.clone(), - b"engine-1".to_vec(), + EngineId::from_engine_index(1).into_frame().to_vec(), |dealer, push| { Box::pin(async move { let utility = recv_engine_message(dealer).await; @@ -2438,6 +2467,7 @@ fn python_msgpack_fixtures_match_rust_encoding() { let stdout = String::from_utf8(output.stdout).unwrap(); let mut lines = stdout.lines(); let request_hex = lines.next().expect("missing request fixture line"); + let defaults_request_hex = lines.next().expect("missing defaults request fixture line"); let multimodal_request_hex = lines.next().expect("missing multimodal request fixture line"); let outputs_hex = lines.next().expect("missing outputs fixture line"); let inline_logprobs_frames = lines.next().expect("missing inline logprobs fixture line"); @@ -2445,6 +2475,7 @@ fn python_msgpack_fixtures_match_rust_encoding() { let inline_prompt_frames = lines.next().expect("missing inline prompt logprobs fixture line"); let multipart_prompt_frames = lines.next().expect("missing multipart prompt logprobs fixture line"); + let ready_response_hex = lines.next().expect("missing ready response fixture line"); let request_bytes = hex::decode(request_hex).unwrap(); let multimodal_request_bytes = hex::decode(multimodal_request_hex).unwrap(); @@ -2454,6 +2485,42 @@ fn python_msgpack_fixtures_match_rust_encoding() { let expected_request = sample_request(); assert_eq!(decoded_request, expected_request); + // All-default sampling params -> empty map; must decode to Python defaults. + let defaults_request_bytes = hex::decode(defaults_request_hex).unwrap(); + let decoded_defaults: EngineCoreRequest = + rmp_serde::from_slice(&defaults_request_bytes).unwrap(); + assert_eq!(decoded_defaults.request_id, "req-defaults"); + let sampling = decoded_defaults + .sampling_params + .expect("defaults request carries sampling params"); + assert_eq!( + sampling, + EngineCoreSamplingParams { + temperature: 1.0, + top_p: 1.0, + top_k: 0, + seed: None, + max_tokens: 16, + min_tokens: 0, + logprobs: None, + prompt_logprobs: None, + min_p: 0.0, + frequency_penalty: 0.0, + presence_penalty: 0.0, + repetition_penalty: 1.0, + stop_token_ids: Vec::new(), + eos_token_id: None, + all_stop_token_ids: BTreeSet::new(), + logit_bias: None, + allowed_token_ids: None, + bad_words_token_ids: None, + structured_outputs: None, + logprob_token_ids: None, + skip_reading_prefix_cache: None, + extra_args: None, + }, + ); + let decoded_multimodal_request: EngineCoreRequest = rmp_serde::from_slice(&multimodal_request_bytes).unwrap(); assert_eq!(decoded_multimodal_request, sample_multimodal_request()); @@ -2554,6 +2621,23 @@ fn python_msgpack_fixtures_match_rust_encoding() { .as_ref() .expect("multipart prompt logprobs decoded"), ); + + let map_keys = |bytes: &[u8]| -> BTreeSet { + match decode_value(bytes) { + Value::Map(entries) => entries + .into_iter() + .filter_map(|(key, _)| key.as_str().map(str::to_owned)) + .collect(), + other => panic!("ready response should encode as a map, got {other:?}"), + } + }; + let python_ready_keys = map_keys(&hex::decode(ready_response_hex).unwrap()); + let rust_ready_keys = + map_keys(&rmp_serde::to_vec_named(&crate::mock_engine::default_ready_response()).unwrap()); + assert_eq!( + rust_ready_keys, python_ready_keys, + "EngineCoreReadyResponse drifted from the Python dataclass", + ); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -2634,6 +2718,90 @@ async fn bootstrapped_connects_with_contiguous_engine_ids() { client.shutdown().await.unwrap(); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn bootstrapped_connects_with_nonzero_engine_start_index() { + init_tracing(); + let ipc = IpcNamespace::new().unwrap(); + let input_address = ipc.input_endpoint(); + let output_address = ipc.output_endpoint(); + + let client_task = tokio::spawn({ + let input_address = input_address.clone(); + let output_address = output_address.clone(); + async move { + EngineCoreClient::connect(bootstrapped_test_config_with_start_index( + input_address, + output_address, + 3, + 1, + Duration::from_secs(2), + 0, + None, + )) + .await + .unwrap() + } + }); + + let (_dealer, _push) = + setup_bootstrapped_mock_engine(input_address, output_address, &[0x03, 0x00]).await; + let client = client_task.await.unwrap(); + + assert_eq!(client.engine_count(), 1); + let engine_ids = + client.engine_identities().into_iter().map(|id| id.to_vec()).collect::>(); + assert_eq!(engine_ids, vec![vec![0x03, 0x00]]); + + client.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn bootstrapped_rejects_unexpected_engine_id_for_start_index() { + init_tracing(); + let ipc = IpcNamespace::new().unwrap(); + let input_address = ipc.input_endpoint(); + let output_address = ipc.output_endpoint(); + + let client_task = tokio::spawn({ + let input_address = input_address.clone(); + let output_address = output_address.clone(); + async move { + EngineCoreClient::connect(bootstrapped_test_config_with_start_index( + input_address, + output_address, + 3, + 1, + Duration::from_secs(2), + 0, + None, + )) + .await + } + }); + + let _ = crate::mock_engine::connect_to_bootstrapped_frontend( + input_address, + output_address, + &[0x00, 0x00], + crate::mock_engine::MockEngineConfig { + local: true, + headless: true, + ..Default::default() + }, + ) + .await; + let error = match client_task.await.unwrap() { + Ok(_) => panic!("bootstrapped connect should reject unexpected engine id"), + Err(error) => error, + }; + + assert!( + error + .to_string() + .contains("received input registration for unexpected engine id") + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn bootstrapped_connect_times_out_without_registration() { init_tracing(); diff --git a/rust/src/engine-core-client/src/tests/python_compat.py b/rust/src/engine-core-client/src/tests/python_compat.py index bb81a6df1ada..8398c874da05 100755 --- a/rust/src/engine-core-client/src/tests/python_compat.py +++ b/rust/src/engine-core-client/src/tests/python_compat.py @@ -10,6 +10,7 @@ # ] # /// +from dataclasses import dataclass from enum import Enum, IntEnum import msgpack @@ -30,12 +31,13 @@ class FinishReason(IntEnum): REPETITION = 4 -class EngineCoreSamplingParams(msgspec.Struct, dict=True): +# Mirror of real SamplingParams; omit_defaults makes fixtures match real maps. +class EngineCoreSamplingParams(msgspec.Struct, dict=True, omit_defaults=True): temperature: float = 1.0 top_p: float = 1.0 top_k: int = 0 seed: int | None = None - max_tokens: int = 65536 + max_tokens: int = 16 min_tokens: int = 0 min_p: float = 0.0 frequency_penalty: float = 0.0 @@ -134,6 +136,16 @@ class EngineCoreOutputs( client_index=0, ) +# All defaults -> empty map. Regression guard for the sparse-map decode. +defaults_request = EngineCoreRequest( + request_id="req-defaults", + prompt_token_ids=[5, 6, 7], + mm_features=None, + sampling_params=EngineCoreSamplingParams(), + pooling_params=None, + arrival_time=1.0, +) + multimodal_tensor = np.array([[1.0, 2.0], [3.5, 4.25]], dtype=np.float32) multimodal_features = [ { @@ -337,7 +349,30 @@ def engine_outputs_wire(output): ) ) + +@dataclass +class EngineCoreReadyResponse: + max_model_len: int + num_gpu_blocks: int + block_size: int + dp_stats_address: str | None + dtype: str + vllm_version: str + kv_cache_size_tokens: int | None = None + kv_cache_max_concurrency: float | None = None + + +ready_response = EngineCoreReadyResponse( + max_model_len=32768, + num_gpu_blocks=1000, + block_size=16, + dp_stats_address=None, + dtype="float32", + vllm_version="0.0.0", +) + print(msgspec.msgpack.encode(request).hex()) +print(msgspec.msgpack.encode(defaults_request).hex()) print(msgpack.packb(multimodal_request_wire, use_bin_type=True).hex()) print(msgspec.msgpack.encode(outputs).hex()) print(" ".join(frame.hex() for frame in encode_output_frames(inline_logprobs))) @@ -354,3 +389,4 @@ def engine_outputs_wire(output): for frame in encode_output_frames(multipart_prompt_logprobs, size_threshold=1) ) ) +print(msgspec.msgpack.encode(ready_response).hex()) diff --git a/rust/src/engine-core-client/src/transport.rs b/rust/src/engine-core-client/src/transport.rs index 360f94eda127..d0d9b4efe39f 100644 --- a/rust/src/engine-core-client/src/transport.rs +++ b/rust/src/engine-core-client/src/transport.rs @@ -327,6 +327,7 @@ pub async fn connect_handshake( pub async fn connect_bootstrapped( input_address: &str, output_address: &str, + engine_start_index: u32, engine_count: usize, ready_timeout: Duration, ) -> Result { @@ -342,8 +343,8 @@ pub async fn connect_bootstrapped( let engines = wait_for_input_registrations( &mut input_socket, - // TODO: follow start rank - (0..engine_count).map(|index| EngineId::from((index as u16).to_le_bytes().to_vec())), + (0..engine_count) + .map(|offset| EngineId::from_engine_index(engine_start_index + offset as u32)), ready_timeout, ) .await?; diff --git a/rust/src/llm/Cargo.toml b/rust/src/llm/Cargo.toml index c7924b85db7e..982fd32dfdab 100644 --- a/rust/src/llm/Cargo.toml +++ b/rust/src/llm/Cargo.toml @@ -11,6 +11,7 @@ test-util = [] easy-ext.workspace = true enum-as-inner.workspace = true futures.workspace = true +parking_lot.workspace = true serde.workspace = true serde_json.workspace = true thiserror.workspace = true diff --git a/rust/src/llm/src/inflight.rs b/rust/src/llm/src/inflight.rs new file mode 100644 index 000000000000..37df1441172a --- /dev/null +++ b/rust/src/llm/src/inflight.rs @@ -0,0 +1,179 @@ +//! Tracking of the external→internal request-id mapping for in-flight requests. +//! +//! When request-id randomization is enabled (the default), [`crate::Llm`] +//! rewrites the external (user-supplied) request id into a unique internal +//! engine id before reaching engine-core. Engine-core only ever knows the +//! internal id, so aborting a request by its external id requires resolving it +//! back to the internal id(s) first. + +use std::collections::HashMap; +use std::sync::{Arc, Weak}; + +use parking_lot::Mutex; + +/// external id → internal id → number of live guards holding that edge. +type InflightMap = HashMap>; + +/// Maps external (user-supplied) request ids to the set of live internal engine +/// request ids they currently expand into. +/// +/// One external id may map to multiple internal ids: duplicate external ids +/// submitted concurrently each get their own randomized internal id, and an +/// abort by the shared external id must reach all of them. Edges are +/// refcounted: with randomization disabled the same (external, internal) pair +/// can be tracked by several guards in sequence (e.g. a finished request whose +/// stream is still held alongside a fresh submission reusing the id), and the +/// edge must survive until the last guard drops. +#[derive(Default)] +pub(crate) struct InflightRequests { + map: Arc>, +} + +impl InflightRequests { + pub(crate) fn new() -> Self { + Self::default() + } + + /// Record that `internal` is now an in-flight engine request for the + /// `external` request id, returning a guard that removes the edge when the + /// request's output stream is dropped (on clean finish or cancellation). + pub(crate) fn track(&self, external: String, internal: String) -> RequestGuard { + *self + .map + .lock() + .entry(external.clone()) + .or_default() + .entry(internal.clone()) + .or_insert(0) += 1; + RequestGuard { + map: Arc::downgrade(&self.map), + external, + internal, + } + } + + /// Resolve external request ids to the internal engine ids currently + /// in-flight for them. Unknown or already-finished ids contribute nothing. + pub(crate) fn resolve(&self, external_ids: &[String]) -> Vec { + let map = self.map.lock(); + external_ids + .iter() + .filter_map(|external| map.get(external)) + .flat_map(|internal_ids| internal_ids.keys()) + .cloned() + .collect() + } + + #[cfg(test)] + fn is_empty(&self) -> bool { + self.map.lock().is_empty() + } +} + +/// RAII guard that releases one refcount on a single external→internal edge +/// when dropped, removing the edge once no live guard holds it. +/// +/// Held by the per-request output stream, so cleanup runs whether the stream +/// terminates cleanly or is cancelled. A [`Weak`] handle is used so a stream +/// outliving its owning [`InflightRequests`] does not keep the map alive. +pub(crate) struct RequestGuard { + map: Weak>, + external: String, + internal: String, +} + +impl Drop for RequestGuard { + fn drop(&mut self) { + let Some(map) = self.map.upgrade() else { + return; + }; + let mut map = map.lock(); + if let Some(internal_ids) = map.get_mut(&self.external) { + if let Some(count) = internal_ids.get_mut(&self.internal) { + *count -= 1; + if *count == 0 { + internal_ids.remove(&self.internal); + } + } + if internal_ids.is_empty() { + map.remove(&self.external); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resolves_external_to_internal() { + let inflight = InflightRequests::new(); + let _guard = inflight.track("ext".to_string(), "ext-abc".to_string()); + + assert_eq!( + inflight.resolve(&["ext".to_string()]), + vec!["ext-abc".to_string()] + ); + assert!(inflight.resolve(&["unknown".to_string()]).is_empty()); + } + + #[test] + fn one_external_maps_to_many_internal() { + let inflight = InflightRequests::new(); + let _g1 = inflight.track("dup".to_string(), "dup-1".to_string()); + let _g2 = inflight.track("dup".to_string(), "dup-2".to_string()); + + let mut resolved = inflight.resolve(&["dup".to_string()]); + resolved.sort(); + assert_eq!(resolved, vec!["dup-1".to_string(), "dup-2".to_string()]); + } + + #[test] + fn dropping_guard_removes_only_its_own_edge_then_cleans_empty_key() { + let inflight = InflightRequests::new(); + let g1 = inflight.track("dup".to_string(), "dup-1".to_string()); + let g2 = inflight.track("dup".to_string(), "dup-2".to_string()); + + drop(g1); + assert_eq!( + inflight.resolve(&["dup".to_string()]), + vec!["dup-2".to_string()] + ); + + drop(g2); + assert!(inflight.resolve(&["dup".to_string()]).is_empty()); + assert!( + inflight.is_empty(), + "empty external key must be removed, not left dangling" + ); + } + + #[test] + fn identical_edges_are_refcounted_across_guards() { + // With request-id randomization disabled, internal == external, so two + // tracked requests can share the exact same edge. Dropping one guard + // (e.g. a stale stream, or the error path of a rejected duplicate + // submission) must not untrack the other still-live request. + let inflight = InflightRequests::new(); + let g1 = inflight.track("x".to_string(), "x".to_string()); + let g2 = inflight.track("x".to_string(), "x".to_string()); + + drop(g1); + assert_eq!(inflight.resolve(&["x".to_string()]), vec!["x".to_string()]); + + drop(g2); + assert!(inflight.resolve(&["x".to_string()]).is_empty()); + assert!(inflight.is_empty()); + } + + #[test] + fn guard_drop_is_a_noop_after_inflight_is_gone() { + let guard = { + let inflight = InflightRequests::new(); + inflight.track("ext".to_string(), "ext-abc".to_string()) + }; + // Dropping the guard after the owning map is gone must not panic. + drop(guard); + } +} diff --git a/rust/src/llm/src/lib.rs b/rust/src/llm/src/lib.rs index 43d46b02f89b..9adfc737b63c 100644 --- a/rust/src/llm/src/lib.rs +++ b/rust/src/llm/src/lib.rs @@ -2,6 +2,7 @@ use tracing::Span; use vllm_engine_core_client::EngineCoreClient; mod error; +mod inflight; mod log_stats; mod output; mod request; @@ -15,18 +16,22 @@ pub use output::{ pub use request::GenerateRequest; pub use vllm_engine_core_client::protocol::logprobs::{Logprobs, PositionLogprobs, TokenLogprob}; +use crate::inflight::InflightRequests; use crate::log_stats::StatsLogger; use crate::request_metrics::RequestMetricsTracker; -/// Thin generate-only facade over [`EngineCoreClient`]. +/// Thin generate-and-abort facade over [`EngineCoreClient`]. /// /// This mirrors the narrow public shape of Python `AsyncLLM.generate()` and /// `abort()`, but keeps the boundary close to raw engine-core requests and -/// outputs. +/// outputs. It tracks an in-flight external→internal request-id index (see +/// [`InflightRequests`]) so that aborts issued against external (user-supplied) +/// ids can be resolved to the internal engine ids that engine-core understands. pub struct Llm { client: EngineCoreClient, randomize_request_id: bool, stats_logger: Option, + inflight: InflightRequests, } impl Llm { @@ -37,6 +42,7 @@ impl Llm { client, randomize_request_id: true, stats_logger: None, + inflight: InflightRequests::new(), } } @@ -72,9 +78,15 @@ impl Llm { pub async fn generate(&self, req: GenerateRequest) -> Result { let prepared = req.prepare(self.randomize_request_id)?; let prompt_token_ids = prepared.prompt_token_ids().into(); + let external_request_id = prepared + .engine_request + .external_req_id + .clone() + .expect("prepare always sets external_req_id"); + let internal_request_id = prepared.engine_request.request_id.clone(); // Record internal engine-core request ID in the current tracing span. - Span::current().record("engine_request_id", &prepared.engine_request.request_id); + Span::current().record("engine_request_id", &internal_request_id); let request_metrics = RequestMetricsTracker::new( self.client.model_name().to_string(), @@ -84,14 +96,32 @@ impl Llm { 1, ); let stream = self.client.call(prepared.engine_request).await?; + let guard = self.inflight.track(external_request_id, internal_request_id); Ok(GenerateOutputStream::new( prompt_token_ids, stream, request_metrics, + guard, )) } + /// Abort in-flight requests by their external (user-supplied) request ids. + /// + /// External ids are resolved to the internal engine ids actually known to + /// engine-core (one external id may map to several internal ids). Unknown + /// or already-finished ids resolve to nothing and are a safe no-op. The + /// tracking entries themselves are removed when the corresponding output + /// streams are dropped, not here. + pub async fn abort(&self, external_ids: &[String]) -> Result<()> { + let internal_ids = self.inflight.resolve(external_ids); + if internal_ids.is_empty() { + return Ok(()); + } + self.client.abort(&internal_ids).await?; + Ok(()) + } + /// Shut down the underlying engine-core client and its background tasks. pub async fn shutdown(self) -> Result<()> { self.client.shutdown().await?; diff --git a/rust/src/llm/src/output.rs b/rust/src/llm/src/output.rs index cca7cdca337b..8cfc38d0bc99 100644 --- a/rust/src/llm/src/output.rs +++ b/rust/src/llm/src/output.rs @@ -12,6 +12,7 @@ use vllm_engine_core_client::protocol::{EngineCoreFinishReason, StopReason}; use vllm_engine_core_client::{AbortCause, EngineCoreOutputStream}; use crate::error::Result; +use crate::inflight::RequestGuard; use crate::request_metrics::{RequestMetricsTracker, current_unix_timestamp_secs}; /// Token usage metadata for one request. @@ -195,12 +196,17 @@ impl GenerateOutput { /// Stream of per-request generate outputs for one request. /// -/// - A normal termination of the stream represents a clean completion of the request. -/// - For errors, unexpected closes, or explicit aborts, the stream terminates with an error. +/// - A normal termination of the stream represents a clean completion of the +/// request, including a client-initiated abort, which yields a final output +/// with `finish_reason = Abort` before the stream ends. +/// - For errors or unexpected engine-side closes, the stream terminates with an error. pub struct GenerateOutputStream { pending_prompt_info: Option, raw_stream: EngineCoreOutputStream, request_metrics: RequestMetricsTracker, + /// Removes this request's external→internal tracking edge on drop. Held for + /// its `Drop` side effect only; never read directly. + _request_guard: RequestGuard, } impl GenerateOutputStream { @@ -210,6 +216,7 @@ impl GenerateOutputStream { prompt_token_ids: Arc<[u32]>, raw_stream: EngineCoreOutputStream, request_metrics: RequestMetricsTracker, + request_guard: RequestGuard, ) -> Self { Self { pending_prompt_info: Some(GeneratePromptInfo { @@ -218,6 +225,7 @@ impl GenerateOutputStream { }), raw_stream, request_metrics, + _request_guard: request_guard, } } diff --git a/rust/src/llm/src/request_metrics.rs b/rust/src/llm/src/request_metrics.rs index d28b83be816b..6612fa3cc4fb 100644 --- a/rust/src/llm/src/request_metrics.rs +++ b/rust/src/llm/src/request_metrics.rs @@ -98,27 +98,33 @@ impl RequestMetricsTracker { self.observe_events(engine_index, events); } - if self.is_prefilling { - if let Some(prefill_stats) = &output.prefill_stats { - record_prompt_tokens(&self.model_name, engine_index, prefill_stats); + // Only outputs that actually carry tokens drive token-timing metrics. + // A terminal output with no new tokens (e.g. the synthesized abort + // output) must not log a stray time-to-first-token or inter-token + // sample. + if !output.new_token_ids.is_empty() { + if self.is_prefilling { + if let Some(prefill_stats) = &output.prefill_stats { + record_prompt_tokens(&self.model_name, engine_index, prefill_stats); + } + self.first_token_latency = received_at - self.arrival_time; + observe_time_to_first_token_seconds( + &self.model_name, + engine_index, + self.first_token_latency, + ); + self.first_token_ts = batch_timestamp; + self.is_prefilling = false; + } else if self.last_token_ts > 0.0 { + observe_inter_token_latency_seconds( + &self.model_name, + engine_index, + batch_timestamp - self.last_token_ts, + ); } - self.first_token_latency = received_at - self.arrival_time; - observe_time_to_first_token_seconds( - &self.model_name, - engine_index, - self.first_token_latency, - ); - self.first_token_ts = batch_timestamp; - self.is_prefilling = false; - } else if self.last_token_ts > 0.0 { - observe_inter_token_latency_seconds( - &self.model_name, - engine_index, - batch_timestamp - self.last_token_ts, - ); - } - self.last_token_ts = batch_timestamp; + self.last_token_ts = batch_timestamp; + } } /// Emit the terminal request metrics once a finished output has been diff --git a/rust/src/llm/tests/generate.rs b/rust/src/llm/tests/generate.rs index 18e05063d9ed..cc7e7f820faf 100644 --- a/rust/src/llm/tests/generate.rs +++ b/rust/src/llm/tests/generate.rs @@ -554,6 +554,142 @@ async fn duplicate_external_request_ids_are_randomized_before_reaching_engine_co llm.shutdown().await.unwrap(); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn abort_resolves_external_request_id_to_internal_before_reaching_engine() { + let ipc = IpcNamespace::new().unwrap(); + let handshake_address = ipc.handshake_endpoint(); + let engine_id = b"engine-abort".to_vec(); + + let (shutdown_tx, engine_task) = spawn_mock_engine_task( + handshake_address.clone(), + engine_id.clone(), + |dealer, push| { + Box::pin(async move { + let add = recv_engine_message(dealer).await; + assert_eq!(add[0].as_ref(), &[0x00]); + let request: EngineCoreRequest = rmp_serde::from_slice(&add[1]).unwrap(); + assert_eq!(request.external_req_id.as_deref(), Some("req-abort")); + assert!(request.request_id.starts_with("req-abort-")); + assert_ne!(request.request_id, "req-abort"); + + send_outputs( + push, + EngineCoreOutputs { + outputs: vec![request_output(&request.request_id, vec![7], None)], + ..Default::default() + }, + ) + .await; + + // The abort frame must carry the internal engine id, not the + // external "req-abort" id the caller aborted by. + let abort = + timeout(Duration::from_secs(1), recv_engine_message(dealer)).await.unwrap(); + assert_eq!(abort[0].as_ref(), &[0x01]); + let aborted_ids: Vec = rmp_serde::from_slice(&abort[1]).unwrap(); + assert_eq!(aborted_ids, vec![request.request_id]); + }) + }, + ); + + let llm = connect_async_llm_with_ipc(handshake_address, 0, "test-model", &ipc).await; + let mut stream = llm.generate(sample_generate_request("req-abort", 4)).await.unwrap(); + let internal_id = stream.request_id().to_string(); + assert_ne!(internal_id, "req-abort"); + + assert_eq!(stream.next().await.unwrap().unwrap().token_ids, vec![7]); + + // Abort by the external id; engine-core only knows the internal id. + llm.abort(&["req-abort".to_string()]).await.unwrap(); + + // The consumer stream is finalized locally with a clean abort terminal + // rather than hanging or surfacing as RequestStreamClosed. The engine sends + // no final output for a client abort, so this output is synthesized. + let terminal = stream.next().await.unwrap().unwrap(); + assert_eq!(terminal.finish_reason, Some(FinishReason::Abort)); + assert!(terminal.token_ids.is_empty()); + assert!(stream.next().await.is_none()); + + let _ = shutdown_tx.send(()); + engine_task.await.unwrap(); + drop(stream); + llm.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn abort_by_external_id_aborts_all_internal_requests() { + let ipc = IpcNamespace::new().unwrap(); + let handshake_address = ipc.handshake_endpoint(); + let engine_id = b"engine-abort-many".to_vec(); + + let (shutdown_tx, engine_task) = spawn_mock_engine_task( + handshake_address.clone(), + engine_id.clone(), + |dealer, push| { + Box::pin(async move { + let add_1 = recv_engine_message(dealer).await; + assert_eq!(add_1[0].as_ref(), &[0x00]); + let request_1: EngineCoreRequest = rmp_serde::from_slice(&add_1[1]).unwrap(); + + let add_2 = recv_engine_message(dealer).await; + assert_eq!(add_2[0].as_ref(), &[0x00]); + let request_2: EngineCoreRequest = rmp_serde::from_slice(&add_2[1]).unwrap(); + + assert_eq!(request_1.external_req_id.as_deref(), Some("req-dup-abort")); + assert_eq!(request_2.external_req_id.as_deref(), Some("req-dup-abort")); + assert_ne!(request_1.request_id, request_2.request_id); + + send_outputs( + push, + EngineCoreOutputs { + outputs: vec![ + request_output(&request_1.request_id, vec![7], None), + request_output(&request_2.request_id, vec![8], None), + ], + ..Default::default() + }, + ) + .await; + + // A single abort by the shared external id must abort both + // internal engine ids it expanded into. + let abort = + timeout(Duration::from_secs(1), recv_engine_message(dealer)).await.unwrap(); + assert_eq!(abort[0].as_ref(), &[0x01]); + let mut aborted_ids: Vec = rmp_serde::from_slice(&abort[1]).unwrap(); + aborted_ids.sort(); + let mut expected = vec![request_1.request_id, request_2.request_id]; + expected.sort(); + assert_eq!(aborted_ids, expected); + }) + }, + ); + + let llm = connect_async_llm_with_ipc(handshake_address, 0, "test-model", &ipc).await; + let mut stream_1 = llm.generate(sample_generate_request("req-dup-abort", 4)).await.unwrap(); + let mut stream_2 = llm.generate(sample_generate_request("req-dup-abort", 4)).await.unwrap(); + assert_ne!(stream_1.request_id(), stream_2.request_id()); + + assert_eq!(stream_1.next().await.unwrap().unwrap().token_ids, vec![7]); + assert_eq!(stream_2.next().await.unwrap().unwrap().token_ids, vec![8]); + + llm.abort(&["req-dup-abort".to_string()]).await.unwrap(); + + // Both internal requests the external id expanded into are finalized with a + // clean abort terminal. + for stream in [&mut stream_1, &mut stream_2] { + let terminal = stream.next().await.unwrap().unwrap(); + assert_eq!(terminal.finish_reason, Some(FinishReason::Abort)); + assert!(stream.next().await.is_none()); + } + + let _ = shutdown_tx.send(()); + engine_task.await.unwrap(); + drop(stream_1); + drop(stream_2); + llm.shutdown().await.unwrap(); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn generate_records_request_metrics_in_prometheus_output() { let ipc = IpcNamespace::new().unwrap(); diff --git a/rust/src/managed-engine/src/cli.rs b/rust/src/managed-engine/src/cli.rs index d70870dc32ae..bbd8e70f909b 100644 --- a/rust/src/managed-engine/src/cli.rs +++ b/rust/src/managed-engine/src/cli.rs @@ -71,7 +71,10 @@ impl ManagedEngineArgs { self, model: String, max_model_len: Option, + max_logprobs: Option, language_model_only: bool, + disable_log_stats: bool, + shutdown_timeout: u64, handshake_port: u16, ) -> ManagedEngineConfig { let mut python_args = self.python_args; @@ -80,9 +83,22 @@ impl ManagedEngineArgs { python_args.push("--max-model-len".to_string()); python_args.push(max_model_len.to_string()); } + if let Some(max_logprobs) = max_logprobs { + python_args.push("--max-logprobs".to_string()); + python_args.push(max_logprobs.to_string()); + } if language_model_only { python_args.push("--language-model-only".to_string()); } + if disable_log_stats { + python_args.push("--disable-log-stats".to_string()); + } + // we must pass through shutdown_timeout to the engine, + // otherwise inflight requests get aborted on shutdown + if shutdown_timeout > 0 { + python_args.push("--shutdown-timeout".to_string()); + python_args.push(shutdown_timeout.to_string()); + } if let Some(data_parallel_size_local) = self.data_parallel_size_local { python_args.push("--data-parallel-size-local".to_string()); python_args.push(data_parallel_size_local.to_string()); diff --git a/rust/src/reasoning-parser/src/lib.rs b/rust/src/reasoning-parser/src/lib.rs index f8f8d7c8726d..1f71e14cef7b 100644 --- a/rust/src/reasoning-parser/src/lib.rs +++ b/rust/src/reasoning-parser/src/lib.rs @@ -19,6 +19,7 @@ mod deepseek_r1; mod delimited; mod gemma4; mod kimi; +mod minimax_m3; mod qwen3; mod seed_oss; mod step3p5; @@ -31,6 +32,7 @@ pub use self::deepseek_r1::DeepSeekR1ReasoningParser; pub(crate) use self::delimited::DelimitedReasoningParser; pub use self::gemma4::Gemma4ReasoningParser; pub use self::kimi::KimiReasoningParser; +pub use self::minimax_m3::MiniMaxM3ReasoningParser; pub use self::qwen3::Qwen3ReasoningParser; pub use self::seed_oss::SeedOssReasoningParser; pub use self::step3p5::Step3p5ReasoningParser; diff --git a/rust/src/reasoning-parser/src/minimax_m3.rs b/rust/src/reasoning-parser/src/minimax_m3.rs new file mode 100644 index 000000000000..69d4e416dfa8 --- /dev/null +++ b/rust/src/reasoning-parser/src/minimax_m3.rs @@ -0,0 +1,98 @@ +use vllm_tokenizer::DynTokenizer; + +use super::{DelimitedReasoningParser, ReasoningDelta, ReasoningParser, Result}; + +const M3_THINK_START: &str = ""; +const M3_THINK_END: &str = ""; + +/// Reasoning parser for MiniMax M3 style outputs. +/// +/// MiniMax M3 uses `...` delimiters. Its chat template may +/// prefill either delimiter depending on the requested thinking mode, so the +/// shared delimited parser derives the starting state from the rendered prompt. +pub struct MiniMaxM3ReasoningParser { + inner: DelimitedReasoningParser, + /// True until the first response text is classified. Only this position may + /// drop a stray `` emitted at the start of a response. + at_response_start: bool, + /// Holds an initial suffix like ` Result { + Ok(Self { + inner: DelimitedReasoningParser::new(tokenizer, M3_THINK_START, M3_THINK_END, false)?, + at_response_start: true, + leading_end_buffer: String::new(), + }) + } + + /// Drop a response-leading `` while preserving later unmatched + /// closers as ordinary content. + fn push_inner(&mut self, delta: &str) -> ReasoningDelta { + if self.at_response_start && !self.inner.in_reasoning() { + self.leading_end_buffer.push_str(delta); + let buffered = std::mem::take(&mut self.leading_end_buffer); + + if buffered.is_empty() { + return ReasoningDelta::default(); + } + if let Some(rest) = buffered.strip_prefix(M3_THINK_END) { + self.at_response_start = false; + return self.inner.push(rest); + } + if M3_THINK_END.starts_with(buffered.as_str()) { + self.leading_end_buffer = buffered; + return ReasoningDelta::default(); + } + + self.at_response_start = false; + return self.inner.push(&buffered); + } + + self.inner.push(delta) + } +} + +fn append_delta(target: &mut ReasoningDelta, delta: ReasoningDelta) { + if let Some(reasoning) = delta.reasoning { + target.push_reasoning(&reasoning); + } + if let Some(content) = delta.content { + target.push_content(&content); + } +} + +impl ReasoningParser for MiniMaxM3ReasoningParser { + fn create(tokenizer: DynTokenizer) -> Result> + where + Self: Sized + 'static, + { + Ok(Box::new(Self::new(tokenizer)?)) + } + + fn initialize(&mut self, prompt_token_ids: &[u32]) -> Result<()> { + self.inner.initialize(prompt_token_ids); + self.at_response_start = true; + self.leading_end_buffer.clear(); + Ok(()) + } + + fn push(&mut self, delta: &str) -> Result { + Ok(self.push_inner(delta)) + } + + fn finish(&mut self) -> Result { + let mut delta = ReasoningDelta::default(); + if !self.leading_end_buffer.is_empty() { + let pending = std::mem::take(&mut self.leading_end_buffer); + self.at_response_start = false; + append_delta(&mut delta, self.inner.push(&pending)); + } + append_delta(&mut delta, self.inner.finish()); + Ok(delta) + } +} diff --git a/rust/src/reasoning-parser/src/tests.rs b/rust/src/reasoning-parser/src/tests.rs index 7e33e0cfc1b9..22c026d35818 100644 --- a/rust/src/reasoning-parser/src/tests.rs +++ b/rust/src/reasoning-parser/src/tests.rs @@ -3,7 +3,8 @@ use std::sync::Arc; use vllm_tokenizer::Tokenizer; use super::{ - DeepSeekR1ReasoningParser, DelimitedReasoningParser, Qwen3ReasoningParser, ReasoningParser, + DeepSeekR1ReasoningParser, DelimitedReasoningParser, MiniMaxM3ReasoningParser, + Qwen3ReasoningParser, ReasoningParser, }; pub(crate) struct FakeTokenizer; @@ -32,6 +33,8 @@ impl Tokenizer for FakeTokenizer { "<|END_THINKING|>" => Some(4), "◁think▷" => Some(5), "◁/think▷" => Some(6), + "" => Some(8), + "" => Some(9), "" => Some(10), "" => Some(11), _ => None, @@ -161,3 +164,66 @@ fn deepseek_r1_stops_scanning_at_last_special_token() { assert_eq!(delta.reasoning.as_deref(), Some("reason")); assert_eq!(delta.content.as_deref(), Some("answer")); } + +#[test] +fn minimax_m3_handles_explicit_think_delimiters() { + let tokenizer = Arc::new(FakeTokenizer); + let mut parser = MiniMaxM3ReasoningParser::new(tokenizer).unwrap(); + + let delta = parser.push("reasonanswer").unwrap(); + assert_eq!(delta.reasoning.as_deref(), Some("reason")); + assert_eq!(delta.content.as_deref(), Some("answer")); +} + +#[test] +fn minimax_m3_drops_leading_end_marker() { + let tokenizer = Arc::new(FakeTokenizer); + let mut parser = MiniMaxM3ReasoningParser::new(tokenizer).unwrap(); + + let delta = parser.push("answer").unwrap(); + assert_eq!(delta.reasoning, None); + assert_eq!(delta.content.as_deref(), Some("answer")); +} + +#[test] +fn minimax_m3_preserves_non_leading_end_marker() { + let tokenizer = Arc::new(FakeTokenizer); + let mut parser = MiniMaxM3ReasoningParser::new(tokenizer).unwrap(); + + let delta = parser.push("XXXYYY").unwrap(); + assert_eq!(delta.reasoning, None); + assert_eq!(delta.content.as_deref(), Some("XXXYYY")); +} + +#[test] +fn minimax_m3_drops_split_leading_end_marker() { + let tokenizer = Arc::new(FakeTokenizer); + let mut parser = MiniMaxM3ReasoningParser::new(tokenizer).unwrap(); + + assert!(parser.push("answer").unwrap(); + assert_eq!(delta.reasoning, None); + assert_eq!(delta.content.as_deref(), Some("answer")); +} + +#[test] +fn minimax_m3_uses_prompt_prefilled_start_marker() { + let tokenizer = Arc::new(FakeTokenizer); + let mut parser = MiniMaxM3ReasoningParser::new(tokenizer).unwrap(); + parser.initialize(&[8]).unwrap(); + + let delta = parser.push("reasonanswer").unwrap(); + assert_eq!(delta.reasoning.as_deref(), Some("reason")); + assert_eq!(delta.content.as_deref(), Some("answer")); +} + +#[test] +fn minimax_m3_uses_prompt_prefilled_end_marker() { + let tokenizer = Arc::new(FakeTokenizer); + let mut parser = MiniMaxM3ReasoningParser::new(tokenizer).unwrap(); + parser.initialize(&[9]).unwrap(); + + let delta = parser.push("answer").unwrap(); + assert_eq!(delta.reasoning, None); + assert_eq!(delta.content.as_deref(), Some("answer")); +} diff --git a/rust/src/server/examples/external_engine_openai_qwen.rs b/rust/src/server/examples/external_engine_openai_qwen.rs index 510149deea7b..6eea1afe703b 100644 --- a/rust/src/server/examples/external_engine_openai_qwen.rs +++ b/rust/src/server/examples/external_engine_openai_qwen.rs @@ -14,8 +14,8 @@ use tokio_util::sync::CancellationToken; use tracing_subscriber::EnvFilter; use vllm_engine_core_client::TransportMode; use vllm_server::{ - ApiServerOptions, ChatTemplateContentFormatOption, Config, CoordinatorMode, HttpListenerMode, - ParserSelection, RendererSelection, serve, + ApiServerOptions, ChatTemplateContentFormatOption, Config, CoordinatorMode, CorsConfig, + HttpListenerMode, ParserSelection, RendererSelection, serve, }; #[derive(Debug, Parser)] @@ -68,7 +68,9 @@ async fn main() -> Result<()> { chat_template: None, default_chat_template_kwargs: None, chat_template_content_format: ChatTemplateContentFormatOption::Auto, + max_logprobs: None, api_server_options: ApiServerOptions::default(), + cors: CorsConfig::default(), api_keys: Vec::new(), disable_log_stats: false, grpc_port: None, diff --git a/rust/src/server/src/config.rs b/rust/src/server/src/config.rs index aa65dc03c2a6..c601bbfb6344 100644 --- a/rust/src/server/src/config.rs +++ b/rust/src/server/src/config.rs @@ -2,7 +2,8 @@ use std::collections::HashMap; use std::fmt; use std::time::Duration; -use anyhow::Result; +use anyhow::{Result, bail}; +use axum::http::{HeaderName, HeaderValue, Method}; use educe::Educe; use serde::Serialize; use serde_json::Value; @@ -45,6 +46,59 @@ pub struct ApiServerOptions { pub enable_request_id_headers: bool, } +/// CORS settings mirroring Python's `CORSMiddleware`; the default is permissive. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct CorsConfig { + /// Allowed origins. `["*"]` allows any origin. + pub allow_origins: Vec, + /// Allowed methods. `["*"]` allows the standard method set. + pub allow_methods: Vec, + /// Allowed request headers. `["*"]` mirrors the requested headers. + pub allow_headers: Vec, + /// Whether to allow credentials (cookies, authorization headers). + pub allow_credentials: bool, +} + +impl Default for CorsConfig { + fn default() -> Self { + Self { + allow_origins: vec!["*".to_string()], + allow_methods: vec!["*".to_string()], + allow_headers: vec!["*".to_string()], + allow_credentials: false, + } + } +} + +impl CorsConfig { + /// Validate that non-wildcard values parse into HTTP types, so the CORS + /// layer can be built infallibly after startup validation has run. + pub fn validate(&self) -> Result<()> { + for origin in &self.allow_origins { + if origin != "*" { + origin.parse::().map_err(|e| { + anyhow::anyhow!("invalid --allowed-origins value {origin:?}: {e}") + })?; + } + } + for method in &self.allow_methods { + if method != "*" { + method.parse::().map_err(|e| { + anyhow::anyhow!("invalid --allowed-methods value {method:?}: {e}") + })?; + } + } + for header in &self.allow_headers { + if header != "*" { + header.parse::().map_err(|e| { + anyhow::anyhow!("invalid --allowed-headers value {header:?}: {e}") + })?; + } + } + Ok(()) + } +} + /// Normalized runtime configuration for the minimal OpenAI-compatible server. #[derive(Educe, Clone, PartialEq, Eq, Serialize)] #[educe(Debug)] @@ -77,8 +131,13 @@ pub struct Config { pub default_chat_template_kwargs: Option>, /// How to serialize `message.content` for chat-template rendering. pub chat_template_content_format: ChatTemplateContentFormatOption, + /// Optional maximum number of top log probabilities accepted by the + /// frontend. `None` delegates to the text layer default. + pub max_logprobs: Option, /// HTTP/API-server behavior switches. pub api_server_options: ApiServerOptions, + /// CORS settings applied to every HTTP response. + pub cors: CorsConfig, /// API keys accepted as bearer tokens for guarded routes. #[serde(skip_serializing)] #[educe(Debug(method(fmt_redacted_api_keys)))] @@ -98,6 +157,15 @@ impl Config { /// startup. pub fn validate(&self) -> Result<()> { vllm_chat::validate_parser_overrides(&self.tool_call_parser, &self.reasoning_parser)?; + self.cors.validate()?; + if let Some(max_logprobs) = self.max_logprobs + && max_logprobs < -1 + { + bail!( + "max_logprobs must be non-negative or -1, got {}", + max_logprobs + ); + } Ok(()) } diff --git a/rust/src/server/src/error.rs b/rust/src/server/src/error.rs index cc425ca076f6..e5a5c1a40db1 100644 --- a/rust/src/server/src/error.rs +++ b/rust/src/server/src/error.rs @@ -1,6 +1,7 @@ use axum::Json; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; +use thiserror_ext::AsReport as _; use thiserror_ext::{Construct, Macro}; use crate::routes::openai::utils::types::{ErrorDetail, ErrorResponse}; @@ -72,3 +73,123 @@ impl IntoResponse for ApiError { (self.status_code(), Json(self.to_error_response())).into_response() } } + +/// Classify a text-pipeline submit failure: request validation failures are +/// the client's fault and map to HTTP 400, mirroring the Python frontend. +/// Everything else stays an internal 500. +pub fn text_submit_error(context: &'static str, error: vllm_text::Error) -> ApiError { + if is_request_validation_error(&error) { + return invalid_request!("{error}"); + } + server_error!("{}: {}", context, error.to_report_string()) +} + +/// Like [`text_submit_error`], for the chat pipeline (which both wraps the +/// text errors and raises its own prompt-length variant). +pub fn chat_submit_error(context: &'static str, error: vllm_chat::Error) -> ApiError { + match &error { + vllm_chat::Error::PromptTooLong { .. } => invalid_request!("{error}"), + vllm_chat::Error::Text(text_error) if is_request_validation_error(text_error) => { + invalid_request!("{error}") + } + _ => server_error!("{}: {}", context, error.to_report_string()), + } +} + +fn is_request_validation_error(error: &vllm_text::Error) -> bool { + matches!( + error, + vllm_text::Error::PromptTooLong { .. } + | vllm_text::Error::EmptyPromptTokenIds { .. } + | vllm_text::Error::Logprobs(_) + | vllm_text::Error::OutOfVocab(_) + // An empty tokenized prompt detected later, at request prepare + // time, surfaces through the transparent Llm wrapper. + | vllm_text::Error::Llm(vllm_llm::Error::EmptyPromptTokenIds { .. }) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prompt_too_long_maps_to_invalid_request() { + let error = vllm_text::Error::PromptTooLong { + max_model_len: 8192, + prompt_len: 9000, + }; + let api_error = text_submit_error("failed to submit completion request", error); + assert_eq!(api_error.status_code(), StatusCode::BAD_REQUEST); + let response = api_error.to_error_response(); + assert_eq!(response.error.error_type, "invalid_request_error"); + assert!(response.error.message.contains("8192")); + assert!(response.error.message.contains("9000")); + } + + #[test] + fn chat_wrapped_prompt_too_long_maps_to_invalid_request() { + let error = vllm_chat::Error::Text(vllm_text::Error::PromptTooLong { + max_model_len: 8192, + prompt_len: 9000, + }); + let api_error = chat_submit_error("failed to submit chat request", error); + assert_eq!(api_error.status_code(), StatusCode::BAD_REQUEST); + } + + #[test] + fn llm_wrapped_empty_prompt_maps_to_invalid_request() { + let error = vllm_text::Error::Llm(vllm_llm::Error::EmptyPromptTokenIds { + request_id: "req-1".to_string(), + }); + let api_error = text_submit_error("failed to submit completion request", error); + assert_eq!(api_error.status_code(), StatusCode::BAD_REQUEST); + } + + #[test] + fn logprobs_validation_maps_to_invalid_request() { + let error = vllm_text::Error::Logprobs(vllm_text::LogprobsError::TooManyCount { + parameter: "logprobs", + requested: 1000, + max_allowed: 20, + }); + let api_error = text_submit_error("failed to submit completion request", error); + assert_eq!(api_error.status_code(), StatusCode::BAD_REQUEST); + let response = api_error.to_error_response(); + assert_eq!(response.error.error_type, "invalid_request_error"); + assert!(response.error.message.contains("logprobs")); + } + + #[test] + fn chat_wrapped_logprobs_validation_maps_to_invalid_request() { + let error = vllm_chat::Error::Text(vllm_text::Error::Logprobs( + vllm_text::LogprobsError::TooManyCount { + parameter: "prompt_logprobs", + requested: 1000, + max_allowed: 20, + }, + )); + let api_error = chat_submit_error("failed to submit chat request", error); + assert_eq!(api_error.status_code(), StatusCode::BAD_REQUEST); + } + + #[test] + fn out_of_vocab_validation_maps_to_invalid_request() { + let error = vllm_text::Error::OutOfVocab(vllm_text::OutOfVocabError { + parameter: "logprob_token_ids", + token_ids: vec![1000], + vocab_size: 1000, + }); + let api_error = text_submit_error("failed to submit completion request", error); + assert_eq!(api_error.status_code(), StatusCode::BAD_REQUEST); + } + + #[test] + fn other_submit_errors_stay_internal() { + let error = vllm_text::Error::Tokenizer("backend exploded".to_string()); + let api_error = text_submit_error("failed to submit completion request", error); + assert_eq!(api_error.status_code(), StatusCode::INTERNAL_SERVER_ERROR); + let response = api_error.to_error_response(); + assert!(response.error.message.starts_with("failed to submit completion request:")); + } +} diff --git a/rust/src/server/src/lib.rs b/rust/src/server/src/lib.rs index e1257e7f636e..a2df7795bec7 100644 --- a/rust/src/server/src/lib.rs +++ b/rust/src/server/src/lib.rs @@ -16,7 +16,7 @@ use std::sync::{Arc, OnceLock}; use anyhow::{Context as _, Result}; use axum::Router; use axum::serve::ListenerExt as _; -pub use config::{ApiServerOptions, Config, CoordinatorMode, HttpListenerMode}; +pub use config::{ApiServerOptions, Config, CoordinatorMode, CorsConfig, HttpListenerMode}; use tokio::net::TcpListener; use tokio::time::{Instant, sleep_until}; use tokio_stream::wrappers::TcpListenerStream; @@ -35,9 +35,24 @@ use crate::routes::build_router; use crate::server_info::ServerInfoSnapshot; use crate::state::AppState; +/// Resolve the public model names accepted by the frontend. +fn effective_served_model_names(model: &str, served_model_name: &[String]) -> Vec { + if served_model_name.is_empty() { + vec![model.to_string()] + } else { + served_model_name.to_vec() + } +} + /// Build the shared application state for one configured model and one engine /// client. async fn build_state(config: &Config) -> Result> { + // If no served names are specified, fall back to the backend model path so + // that the API always has at least one valid model ID. Use the same primary + // public name for frontend-side metrics labels. + let served_model_names = effective_served_model_names(&config.model, &config.served_model_name); + let metrics_model_name = served_model_names[0].clone(); + // Load both backends from the same model metadata so they stay in sync. let loaded = load_model_backends( &config.model, @@ -68,32 +83,25 @@ async fn build_state(config: &Config) -> Result> { let client = EngineCoreClient::connect(EngineCoreClientConfig { transport_mode: config.transport_mode.clone(), coordinator_mode, - model_name: config.model.clone(), + model_name: metrics_model_name, client_index: 0, }) .await .context("failed to connect to engine core")?; let llm = Llm::new(client).with_log_stats(!config.disable_log_stats); - let text = TextLlm::new(llm, text_backend); + let text = TextLlm::new(llm, text_backend).with_max_logprobs(config.max_logprobs); let chat = ChatLlm::new(text, chat_backend) .with_tool_call_parser(config.tool_call_parser.clone()) .with_reasoning_parser(config.reasoning_parser.clone()); - // If no served names are specified, fall back to the backend model path so - // that the API always has at least one valid model ID. - let served_model_names = if config.served_model_name.is_empty() { - vec![config.model.clone()] - } else { - config.served_model_name.clone() - }; - Ok(Arc::new( AppState::new(served_model_names, chat) .with_api_server_options(config.api_server_options) .with_server_info(ServerInfoSnapshot::from_config(config)) - .with_api_keys(config.api_keys.clone()), + .with_api_keys(config.api_keys.clone()) + .with_cors(config.cors.clone()), )) } @@ -258,3 +266,26 @@ where .unwrap_or_else(|| Instant::now() + config.shutdown_timeout); state.shutdown(shutdown_deadline).await } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn effective_served_model_names_falls_back_to_backend_model() { + assert_eq!( + effective_served_model_names("backend-model", &[]), + vec!["backend-model"] + ); + } + + #[test] + fn effective_served_model_names_preserves_public_names() { + let served_names = vec!["public-model".to_string(), "public-alias".to_string()]; + + assert_eq!( + effective_served_model_names("backend-model", &served_names), + served_names + ); + } +} diff --git a/rust/src/server/src/middleware/cors.rs b/rust/src/server/src/middleware/cors.rs new file mode 100644 index 000000000000..bd158880e199 --- /dev/null +++ b/rust/src/server/src/middleware/cors.rs @@ -0,0 +1,141 @@ +//! CORS support mirroring Python's Starlette `CORSMiddleware`. +//! +//! Built on `tower_http::cors::CorsLayer`, configured to reproduce Starlette's +//! `CORSMiddleware` behavior for the `--allowed-origins` / `--allowed-methods` / +//! `--allowed-headers` / `--allow-credentials` settings. Two intentional +//! behavioral differences remain, both invisible to real clients: +//! +//! - A rejected preflight returns `200` (empty) rather than Starlette's +//! `400 "Disallowed CORS ..."`. The browser denies the request either way +//! (the disallowed `Access-Control-Allow-*` headers are simply absent), and +//! tower-http makes the preflight reject decision inside its short-circuit, +//! so matching the `400` would mean re-implementing the layer. +//! - A bare `OPTIONS` (no `Access-Control-Request-Method`) returns `200` +//! rather than `405`. No real client sends one. + +use std::time::Duration; + +use axum::extract::Request; +use axum::http::{HeaderName, HeaderValue, Method, header}; +use axum::middleware::Next; +use axum::response::Response; +use tower_http::cors::{AllowHeaders, AllowMethods, AllowOrigin, CorsLayer}; + +use crate::config::CorsConfig; + +/// The method set that `"*"` expands to. +const ALL_METHODS: [Method; 7] = [ + Method::DELETE, + Method::GET, + Method::HEAD, + Method::OPTIONS, + Method::PATCH, + Method::POST, + Method::PUT, +]; + +/// Headers always treated as allowed (the CORS safelist). +const SAFELISTED_HEADERS: [&str; 4] = [ + "accept", + "accept-language", + "content-language", + "content-type", +]; + +fn is_wildcard(values: &[String]) -> bool { + values.iter().any(|value| value == "*") +} + +/// Build a `CorsLayer` from the resolved [`CorsConfig`]. +/// +/// Values are assumed valid: [`CorsConfig::validate`] runs at startup before +/// the router is built. +pub fn cors_layer(cfg: &CorsConfig) -> CorsLayer { + let wildcard_origins = is_wildcard(&cfg.allow_origins); + + let allow_origin = if wildcard_origins { + if cfg.allow_credentials { + // `*` with credentials is illegal, so reflect the request origin + // instead; this also avoids tower-http's wildcard+credentials panic. + AllowOrigin::mirror_request() + } else { + AllowOrigin::any() + } + } else { + AllowOrigin::list( + cfg.allow_origins + .iter() + .map(|origin| origin.parse::().expect("validated origin")) + .collect::>(), + ) + }; + + // Expand `*` to an explicit list rather than `Any`, so we emit the method + // names (not `*`) and never hit tower-http's `Any`+credentials panic. + let allow_methods = if is_wildcard(&cfg.allow_methods) { + AllowMethods::list(ALL_METHODS) + } else { + AllowMethods::list( + cfg.allow_methods + .iter() + .map(|method| method.parse::().expect("validated method")) + .collect::>(), + ) + }; + + let allow_headers = if is_wildcard(&cfg.allow_headers) { + // `*` mirrors the requested headers. + AllowHeaders::mirror_request() + } else { + // Union the safelisted headers, lowercased and sorted. + let mut names: Vec = SAFELISTED_HEADERS.iter().map(|s| s.to_string()).collect(); + names.extend(cfg.allow_headers.iter().map(|h| h.to_ascii_lowercase())); + names.sort(); + names.dedup(); + AllowHeaders::list( + names + .iter() + .map(|header| header.parse::().expect("validated header")) + .collect::>(), + ) + }; + + // Emit `Vary: Origin` only when the allow-origin is dynamic (explicit + // origins, or credentials); the wildcard + no-credentials case emits no + // `Vary` at all, and an empty list disables the header here. + let vary: Vec = if !wildcard_origins || cfg.allow_credentials { + vec![header::ORIGIN] + } else { + vec![] + }; + + CorsLayer::new() + .allow_origin(allow_origin) + .allow_methods(allow_methods) + .allow_headers(allow_headers) + .allow_credentials(cfg.allow_credentials) + .max_age(Duration::from_secs(600)) + .vary(vary) +} + +/// Strip CORS response headers when the request carried no `Origin`. +/// +/// A request without an `Origin` should carry no CORS headers, but tower-http +/// emits `Vary` and `Access-Control-Allow-*` unconditionally. Removing them on +/// no-`Origin` requests keeps non-CORS responses (e.g. `/health`, plain `curl`) +/// clean. +pub async fn strip_cors_on_no_origin(req: Request, next: Next) -> Response { + let had_origin = req.headers().contains_key(header::ORIGIN); + let mut response = next.run(req).await; + if !had_origin { + let headers = response.headers_mut(); + headers.remove(header::VARY); + headers.remove(header::ACCESS_CONTROL_ALLOW_ORIGIN); + headers.remove(header::ACCESS_CONTROL_ALLOW_CREDENTIALS); + headers.remove(header::ACCESS_CONTROL_ALLOW_METHODS); + headers.remove(header::ACCESS_CONTROL_ALLOW_HEADERS); + headers.remove(header::ACCESS_CONTROL_MAX_AGE); + headers.remove(header::ACCESS_CONTROL_EXPOSE_HEADERS); + } + response +} diff --git a/rust/src/server/src/middleware/mod.rs b/rust/src/server/src/middleware/mod.rs index a9d79d49a0ae..65d7b25b026b 100644 --- a/rust/src/server/src/middleware/mod.rs +++ b/rust/src/server/src/middleware/mod.rs @@ -1,9 +1,11 @@ mod auth; +mod cors; mod load; mod metrics; mod request_id; pub use auth::authenticate_api_key; +pub use cors::{cors_layer, strip_cors_on_no_origin}; pub use load::track_server_load; pub use metrics::track_http_metrics; pub use request_id::set_request_id_header; diff --git a/rust/src/server/src/routes.rs b/rust/src/server/src/routes.rs index 481c4da4613b..3826ad40db7b 100644 --- a/rust/src/server/src/routes.rs +++ b/rust/src/server/src/routes.rs @@ -1,3 +1,4 @@ +mod abort_requests; mod cache; mod collective_rpc; mod health; @@ -91,6 +92,7 @@ fn build_router_with_options( .route("/reset_mm_cache", post(cache::reset_mm_cache)) .route("/reset_encoder_cache", post(cache::reset_encoder_cache)) .route("/collective_rpc", post(collective_rpc::collective_rpc)) + .route("/abort_requests", post(abort_requests::abort_requests)) .route("/sleep", post(sleep::sleep)) .route("/wake_up", post(sleep::wake_up)) .route("/is_sleeping", get(sleep::is_sleeping)) @@ -108,7 +110,9 @@ fn build_router_with_options( state.clone(), middleware::track_server_load, )) - .layer(from_fn(middleware::track_http_metrics)); + .layer(from_fn(middleware::track_http_metrics)) + .layer(middleware::cors_layer(&state.cors)) + .layer(from_fn(middleware::strip_cors_on_no_origin)); if enable_api_key_auth { router = router.layer(from_fn_with_state( diff --git a/rust/src/server/src/routes/abort_requests.rs b/rust/src/server/src/routes/abort_requests.rs new file mode 100644 index 000000000000..34fb041c800e --- /dev/null +++ b/rust/src/server/src/routes/abort_requests.rs @@ -0,0 +1,37 @@ +use std::sync::Arc; + +use axum::Json; +use axum::extract::State; +use axum::extract::rejection::JsonRejection; +use axum::http::StatusCode; +use serde::Deserialize; + +use crate::error::ApiError; +use crate::state::AppState; +use crate::utils::utility_call_error; + +#[derive(Debug, Deserialize)] +pub(crate) struct AbortRequestsRequest { + request_ids: Option>, +} + +pub async fn abort_requests( + State(state): State>, + body: Result, JsonRejection>, +) -> Result { + let Json(body) = body.map_err(|error| ApiError::json_parse_error(error.body_text()))?; + let request_ids = body.request_ids.ok_or_else(|| { + ApiError::invalid_request( + "Missing 'request_ids' in request body".to_string(), + Some("request_ids"), + ) + })?; + + state + .chat + .abort(&request_ids) + .await + .map_err(|error| utility_call_error("abort_requests", error))?; + + Ok(StatusCode::OK) +} diff --git a/rust/src/server/src/routes/inference/generate.rs b/rust/src/server/src/routes/inference/generate.rs index ffbf28048daa..c11e4c79ca53 100644 --- a/rust/src/server/src/routes/inference/generate.rs +++ b/rust/src/server/src/routes/inference/generate.rs @@ -28,7 +28,7 @@ use self::types::{ GenerateResponseStreamChoice, GenerateStreamResponse, }; use crate::config::ApiServerOptions; -use crate::error::{ApiError, bail_server_error, server_error}; +use crate::error::{ApiError, bail_server_error, server_error, text_submit_error}; use crate::routes::openai::utils::logprobs::clamp_logprob; use crate::routes::openai::utils::types::{ChatLogProbs, ChatLogProbsContent, TopLogProb, Usage}; use crate::routes::openai::utils::validated_json::ValidatedJson; @@ -65,11 +65,8 @@ pub async fn generate( { Ok(stream) => stream, Err(error) => { - return server_error!( - "failed to submit raw generate request: {}", - error.to_report_string() - ) - .into_response(); + return text_submit_error("failed to submit raw generate request", error) + .into_response(); } }; diff --git a/rust/src/server/src/routes/openai/chat_completions.rs b/rust/src/server/src/routes/openai/chat_completions.rs index 6274a4e98ace..60cd14f9a812 100644 --- a/rust/src/server/src/routes/openai/chat_completions.rs +++ b/rust/src/server/src/routes/openai/chat_completions.rs @@ -25,7 +25,7 @@ use vllm_engine_core_client::protocol::StopReason; use self::convert::{ResponseOptions, prepare_chat_request}; use crate::config::ApiServerOptions; -use crate::error::{ApiError, bail_server_error, server_error}; +use crate::error::{ApiError, bail_server_error, chat_submit_error, server_error}; use crate::routes::openai::chat_completions::types::{ AssistantRole, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatCompletionResponse, ChatCompletionStreamChoice, ChatCompletionStreamResponse, @@ -53,13 +53,6 @@ pub async fn chat_completions( let request_context = resolve_request_context(&headers, body.request_id.as_deref()); let lora_resolution = state.resolve_model_with_loras(Some(&body.model)).await; - if let Err(err) = validate::validate_token_id_ranges( - &body, - state.tokenizer_vocab_size(), - state.model_vocab_size(), - ) { - return err.into_response(); - } let prepared = match prepare_chat_request(body, &lora_resolution, request_context) { Ok(prepared) => prepared, Err(error) => return error.into_response(), @@ -77,11 +70,7 @@ pub async fn chat_completions( match state.chat.chat(prepared.chat_request).instrument(request_span.clone()).await { Ok(stream) => stream, Err(error) => { - return server_error!( - "failed to submit chat request: {}", - error.to_report_string() - ) - .into_response(); + return chat_submit_error("failed to submit chat request", error).into_response(); } }; diff --git a/rust/src/server/src/routes/openai/chat_completions/convert.rs b/rust/src/server/src/routes/openai/chat_completions/convert.rs index aa430db76cc6..bc581842da12 100644 --- a/rust/src/server/src/routes/openai/chat_completions/convert.rs +++ b/rust/src/server/src/routes/openai/chat_completions/convert.rs @@ -142,6 +142,7 @@ pub(super) fn prepare_chat_request( }, tools: convert_tools(request.tools)?, tool_choice: convert_tool_choice(request.tool_choice.as_ref())?, + parallel_tool_calls: request.parallel_tool_calls.unwrap_or(true), decode_options: vllm_text::output::TextDecodeOptions { skip_special_tokens: request.skip_special_tokens, include_stop_str_in_output: request.include_stop_str_in_output, @@ -412,6 +413,33 @@ mod tests { } } + #[test] + fn prepare_chat_request_maps_parallel_tool_calls() { + let mut request = base_request(); + request.parallel_tool_calls = Some(false); + + let prepared = prepare_chat_request( + request, + &served(&["Qwen/Qwen1.5-0.5B-Chat"]), + ResolvedRequestContext::default(), + ) + .expect("request is valid"); + + assert!(!prepared.chat_request.parallel_tool_calls); + } + + #[test] + fn prepare_chat_request_defaults_parallel_tool_calls_to_true() { + let prepared = prepare_chat_request( + base_request(), + &served(&["Qwen/Qwen1.5-0.5B-Chat"]), + ResolvedRequestContext::default(), + ) + .expect("request is valid"); + + assert!(prepared.chat_request.parallel_tool_calls); + } + #[test] fn prepare_chat_request_maps_text_parts() { let mut request = base_request(); diff --git a/rust/src/server/src/routes/openai/chat_completions/validate.rs b/rust/src/server/src/routes/openai/chat_completions/validate.rs index a623925e6494..bbf32c695041 100644 --- a/rust/src/server/src/routes/openai/chat_completions/validate.rs +++ b/rust/src/server/src/routes/openai/chat_completions/validate.rs @@ -1,6 +1,5 @@ use super::types::ChatCompletionRequest; use crate::error::{ApiError, bail_invalid_request}; -use crate::routes::openai::utils::token_ids::{validate_allowed_token_ids, validate_logit_bias}; use crate::routes::openai::utils::types::{ChatMessage, Tool, ToolChoice, ToolChoiceValue}; /// Enforce the minimal compatibility contract for the Rust OpenAI server. @@ -93,13 +92,6 @@ pub(super) fn validate_request_compat( // ---- Reject parameters that are accepted for deserialization but not yet // implemented ---- - if request.parallel_tool_calls.is_some() { - bail_invalid_request!( - param = "parallel_tool_calls", - "parallel_tool_calls is not supported." - ); - } - reject_non_default( request.length_penalty.as_ref(), "length_penalty", @@ -161,21 +153,6 @@ fn validate_function_tools(tools: &[Tool], param: &'static str) -> Result<(), Ap Ok(()) } -/// Reject out-of-vocab token ids, mirroring the Python input processor: -/// `allowed_token_ids` against the tokenizer vocab, `logit_bias` keys against the -/// model vocab (skipped when the model size is unknown). -pub(super) fn validate_token_id_ranges( - request: &ChatCompletionRequest, - tokenizer_vocab_size: usize, - model_vocab_size: Option, -) -> Result<(), ApiError> { - validate_allowed_token_ids(request.allowed_token_ids.as_deref(), tokenizer_vocab_size)?; - validate_logit_bias( - request.logit_bias.as_ref(), - model_vocab_size.unwrap_or(usize::MAX), - ) -} - #[cfg(test)] mod tests { use std::collections::HashMap; @@ -183,7 +160,7 @@ mod tests { use serde_json::json; use vllm_chat::ReasoningEffort; - use super::{validate_request_compat, validate_token_id_ranges}; + use super::validate_request_compat; use crate::routes::openai::chat_completions::types::ChatCompletionRequest; use crate::routes::openai::utils::structured_outputs::ResponseFormat; use crate::routes::openai::utils::types::{ @@ -195,32 +172,6 @@ mod tests { names.iter().map(|s| s.to_string()).collect() } - #[test] - fn validate_token_id_ranges_rejects_oob_and_accepts_in_vocab() { - // allowed_token_ids are bounded by the tokenizer vocab - let mut request = base_request(); - request.allowed_token_ids = Some(vec![5, 1_000_000]); - assert!(validate_token_id_ranges(&request, 100, Some(200)).is_err()); - // logit_bias is bounded by the larger model vocab: an id between the two - // vocabs is valid and must not be rejected (the parity regression we fix) - let mut request = base_request(); - request.logit_bias = Some(HashMap::from([("150".to_string(), 1.0)])); - assert!(validate_token_id_ranges(&request, 100, Some(200)).is_ok()); - // logit_bias beyond the model vocab -> reject - let mut request = base_request(); - request.logit_bias = Some(HashMap::from([("1000000".to_string(), 1.0)])); - assert!(validate_token_id_ranges(&request, 100, Some(200)).is_err()); - // all in-vocab -> accept - let mut request = base_request(); - request.allowed_token_ids = Some(vec![5, 50]); - request.logit_bias = Some(HashMap::from([("50".to_string(), 1.0)])); - assert!(validate_token_id_ranges(&request, 100, Some(200)).is_ok()); - // unknown sizes -> skip - let mut request = base_request(); - request.allowed_token_ids = Some(vec![1_000_000]); - assert!(validate_token_id_ranges(&request, usize::MAX, None).is_ok()); - } - fn base_request() -> ChatCompletionRequest { ChatCompletionRequest { model: "Qwen/Qwen1.5-0.5B-Chat".to_string(), diff --git a/rust/src/server/src/routes/openai/completions.rs b/rust/src/server/src/routes/openai/completions.rs index 9dc2e19154f3..95fb4db9a6f1 100644 --- a/rust/src/server/src/routes/openai/completions.rs +++ b/rust/src/server/src/routes/openai/completions.rs @@ -2,6 +2,7 @@ mod convert; mod types; mod validate; +use std::collections::HashMap; use std::convert::Infallible; use std::result::Result; use std::sync::Arc; @@ -16,16 +17,19 @@ use futures::{Stream, StreamExt as _, pin_mut}; use thiserror_ext::AsReport as _; use tracing::{debug, error, info, trace}; use tracing_futures::Instrument as _; -use vllm_text::{DecodedTextEvent, FinishReason, TextOutputStream, TextOutputStreamExt as _}; +use vllm_text::{ + DecodedPromptLogprobs, DecodedTextEvent, FinishReason, TextOutputStream, + TextOutputStreamExt as _, +}; use self::convert::{ResponseOptions, prepare_completion_request}; use super::utils::logprobs::{ collected_logprobs_to_openai, decoded_logprobs_to_openai, decoded_prompt_logprobs_to_maps, - text_len, + decoded_prompt_logprobs_to_openai, text_len, }; use super::utils::types::Usage; use crate::config::ApiServerOptions; -use crate::error::{ApiError, bail_server_error, server_error}; +use crate::error::{ApiError, bail_server_error, server_error, text_submit_error}; use crate::routes::openai::completions::types::{ CompletionChoice, CompletionRequest, CompletionResponse, CompletionSseChunk, CompletionStreamChoice, CompletionStreamResponse, @@ -47,13 +51,6 @@ pub async fn completions( let request_context = resolve_request_context(&headers, body.request_id.as_deref()); let lora_resolution = state.resolve_model_with_loras(Some(&body.model)).await; - if let Err(err) = validate::validate_token_id_ranges( - &body, - state.tokenizer_vocab_size(), - state.model_vocab_size(), - ) { - return err.into_response(); - } let prepared = match prepare_completion_request(body, &lora_resolution, request_context) { Ok(prepared) => prepared, Err(error) => return error.into_response(), @@ -75,11 +72,7 @@ pub async fn completions( { Ok(stream) => stream, Err(error) => { - return server_error!( - "failed to submit completion request: {}", - error.to_report_string() - ) - .into_response(); + return text_submit_error("failed to submit completion request", error).into_response(); } }; @@ -130,6 +123,7 @@ async fn collect_completion( include_usage: _, // Ignored: non-streaming responses are collected before usage is attached. include_continuous_usage: _, + prompt_only, echo, requested_logprobs, include_prompt_logprobs, @@ -147,17 +141,17 @@ async fn collect_completion( .map(|sr| serde_json::to_value(sr).expect("StopReason must serialize to JSON")); let prompt_char_count = echo.as_ref().map(|prompt| text_len(prompt)).unwrap_or_default(); - let prompt_logprobs = if include_prompt_logprobs { - let prompt_logprobs = collected.prompt_logprobs.as_ref().ok_or_else(|| { - server_error!( - "completion response requested prompt_logprobs but generation returned none" - ) + let logprobs = if requested_logprobs.is_some() && prompt_only { + let prompt = echo.as_deref().ok_or_else(|| { + server_error!("prompt-only completion response missing echoed prompt") })?; - Some(prompt_logprobs) - } else { - None - }; - let logprobs = if requested_logprobs.is_some() { + Some(prompt_only_logprobs_to_openai( + collected.prompt_logprobs.as_ref(), + prompt, + collected.prompt_token_ids.as_ref(), + return_tokens_as_token_ids, + )?) + } else if requested_logprobs.is_some() { Some(collected_logprobs_to_openai( &collected, echo.is_some(), @@ -167,10 +161,18 @@ async fn collect_completion( } else { None }; - let prompt_logprobs = - prompt_logprobs.map(|lp| decoded_prompt_logprobs_to_maps(lp, return_tokens_as_token_ids)); + let prompt_logprobs = if include_prompt_logprobs { + Some(prompt_logprobs_to_maps( + collected.prompt_logprobs.as_ref(), + collected.prompt_token_ids.as_ref(), + return_tokens_as_token_ids, + )?) + } else { + None + }; let text = match &echo { None => collected.text, + Some(prompt) if prompt_only => prompt.clone(), Some(prompt) => format!("{prompt}{}", collected.text), }; let finish_reason = completion_finish_reason_to_openai(finish_reason)?.to_string(); @@ -222,6 +224,7 @@ async fn completion_chunk_stream( ResponseOptions { include_usage, include_continuous_usage, + prompt_only, echo, requested_logprobs, // Ignored: streaming prompt logprobs are rejected for Python parity. @@ -250,14 +253,30 @@ async fn completion_chunk_stream( while let Some(next) = stream.next().await { match next { Ok(DecodedTextEvent::Start { - prompt_token_ids, .. + prompt_token_ids, + prompt_logprobs, }) => { debug!("completion stream started"); continuous_usage.set_prompt_tokens(prompt_token_ids.len()); if let Some(prompt) = echo.as_ref() { visible_text_len = text_len(prompt); - let mut chunk = - delta_chunk(&request_id, &response_model, created, prompt.clone(), None); + let logprobs = if prompt_only && requested_logprobs.is_some() { + Some(prompt_only_logprobs_to_openai( + prompt_logprobs.as_ref(), + prompt, + prompt_token_ids.as_ref(), + return_tokens_as_token_ids, + )?) + } else { + None + }; + let mut chunk = delta_chunk( + &request_id, + &response_model, + created, + prompt.clone(), + logprobs, + ); if return_token_ids && first_chunk { if let Some(choice) = chunk.choices.first_mut() { choice.prompt_token_ids = Some(prompt_token_ids.to_vec()); @@ -282,6 +301,48 @@ async fn completion_chunk_stream( logprobs, finished, }) => { + // Prompt-only streaming already emitted the echoed prompt in the Start chunk. + // The one generated token is only used to drive the engine to a finished event, + // so hide its delta and forward only the terminal finish/usage metadata. + if prompt_only { + if let Some(finished) = finished { + if enable_log_requests { + info!( + stream = true, + model = %response_model, + prompt_tokens = finished.usage.prompt_token_count, + output_tokens = finished.usage.output_token_count, + finish_reason = finished.finish_reason.as_str(), + "completion finished" + ); + } + continuous_usage.set_final_counts( + finished.usage.prompt_token_count, + finished.usage.output_token_count, + ); + let final_chunk = final_chunk( + &request_id, + &response_model, + created, + finished.finish_reason, + )?; + yield_chunk!(final_chunk); + + if include_usage { + y.yield_ok(CompletionSseChunk::Usage(usage_chunk( + &request_id, + &response_model, + created, + Usage::from_token_usage( + finished.usage, + enable_prompt_tokens_details, + ), + ))) + .await; + } + } + continue; + } let delta_text_len = text_len(&delta); let logprobs = if requested_logprobs.is_some() { let decoded_logprobs = logprobs.as_ref().ok_or_else(|| { @@ -397,6 +458,57 @@ fn completion_finish_reason_to_openai( } } +fn prompt_only_logprobs_to_openai( + prompt_logprobs: Option<&DecodedPromptLogprobs>, + prompt: &str, + prompt_token_ids: &[u32], + return_tokens_as_token_ids: bool, +) -> Result { + if let Some(prompt_logprobs) = prompt_logprobs { + return decoded_prompt_logprobs_to_openai(prompt_logprobs, 0, return_tokens_as_token_ids); + } + + if let [token_id] = prompt_token_ids { + let token = if return_tokens_as_token_ids { + format!("token_id:{token_id}") + } else { + prompt.to_string() + }; + + return Ok(LogProbs { + tokens: vec![token], + token_logprobs: vec![None], + top_logprobs: vec![None], + text_offset: vec![0], + }); + } + + Err(server_error!( + "prompt-only completion requested logprobs but generation returned none" + )) +} + +fn prompt_logprobs_to_maps( + prompt_logprobs: Option<&DecodedPromptLogprobs>, + prompt_token_ids: &[u32], + return_tokens_as_token_ids: bool, +) -> Result>>, ApiError> { + if let Some(prompt_logprobs) = prompt_logprobs { + return Ok(decoded_prompt_logprobs_to_maps( + prompt_logprobs, + return_tokens_as_token_ids, + )); + } + + if let [_token_id] = prompt_token_ids { + return Ok(vec![None]); + } + + Err(server_error!( + "completion response requested prompt_logprobs but generation returned none" + )) +} + fn usage_chunk( request_id: &str, response_model: &str, @@ -460,8 +572,8 @@ mod tests { use futures::{StreamExt as _, stream}; use itertools::Itertools as _; use vllm_text::{ - DecodedLogprobs, DecodedPositionLogprobs, DecodedTextEvent, DecodedTokenLogprob, - FinishReason, Finished, + DecodedLogprobs, DecodedPositionLogprobs, DecodedPromptLogprobs, DecodedTextEvent, + DecodedTokenLogprob, FinishReason, Finished, }; use super::{ @@ -624,4 +736,314 @@ mod tests { CompletionSseChunk::Chunk(_) => panic!("expected usage chunk"), } } + + #[tokio::test] + async fn collect_completion_hides_internal_prompt_only_token() { + let stream = stream::iter(vec![ + Ok(DecodedTextEvent::Start { + prompt_token_ids: vec![1, 2].into(), + prompt_logprobs: None, + }), + Ok(DecodedTextEvent::TextDelta { + delta: " leaked".to_string(), + token_ids: vec![3], + logprobs: None, + finished: Some(Finished { + usage: vllm_llm::TokenUsage { + prompt_token_count: 2, + output_token_count: 1, + cached_token_count: 0, + }, + finish_reason: FinishReason::Length, + kv_transfer_params: None, + }), + }), + ]); + + let response = super::collect_completion( + stream, + "cmpl-1".to_string(), + "model".to_string(), + 1, + ApiServerOptions::default(), + ResponseOptions { + prompt_only: true, + echo: Some("hello".to_string()), + return_token_ids: true, + ..Default::default() + }, + ) + .await + .expect("collect completion"); + + assert_eq!(response.choices[0].text, "hello"); + assert_eq!(response.choices[0].token_ids.as_deref(), Some(&[3][..])); + assert_eq!( + response.choices[0].prompt_token_ids.as_deref(), + Some(&[1, 2][..]) + ); + let usage = response.usage.expect("usage"); + assert_eq!(usage.prompt_tokens, 2); + assert_eq!(usage.completion_tokens, Some(1)); + assert_eq!(usage.total_tokens, 3); + } + + #[tokio::test] + async fn collect_completion_maps_prompt_logprobs_for_single_token_prompt() { + let stream = stream::iter(vec![ + Ok(DecodedTextEvent::Start { + prompt_token_ids: vec![9707].into(), + prompt_logprobs: None, + }), + Ok(DecodedTextEvent::TextDelta { + delta: " leaked".to_string(), + token_ids: vec![3], + logprobs: None, + finished: Some(Finished { + usage: vllm_llm::TokenUsage { + prompt_token_count: 1, + output_token_count: 1, + cached_token_count: 0, + }, + finish_reason: FinishReason::Length, + kv_transfer_params: None, + }), + }), + ]); + + let response = super::collect_completion( + stream, + "cmpl-1".to_string(), + "model".to_string(), + 1, + ApiServerOptions::default(), + ResponseOptions { + prompt_only: true, + echo: Some("Hello".to_string()), + requested_logprobs: Some(1), + include_prompt_logprobs: true, + ..Default::default() + }, + ) + .await + .expect("collect completion"); + + let choice = &response.choices[0]; + assert_eq!(choice.text, "Hello"); + assert_eq!(choice.prompt_logprobs, Some(vec![None])); + let logprobs = choice.logprobs.as_ref().expect("logprobs"); + assert_eq!(logprobs.tokens, vec!["Hello".to_string()]); + assert_eq!(logprobs.token_logprobs, vec![None]); + assert_eq!(logprobs.top_logprobs, vec![None]); + assert_eq!(logprobs.text_offset, vec![0]); + let usage = response.usage.expect("usage"); + assert_eq!(usage.prompt_tokens, 1); + assert_eq!(usage.completion_tokens, Some(1)); + assert_eq!(usage.total_tokens, 2); + } + + #[tokio::test] + async fn completion_chunk_stream_hides_internal_prompt_only_token() { + let stream = stream::iter(vec![ + Ok(DecodedTextEvent::Start { + prompt_token_ids: vec![1, 2].into(), + prompt_logprobs: None, + }), + Ok(DecodedTextEvent::TextDelta { + delta: " leaked".to_string(), + token_ids: vec![3], + logprobs: None, + finished: Some(Finished { + usage: vllm_llm::TokenUsage { + prompt_token_count: 2, + output_token_count: 1, + cached_token_count: 0, + }, + finish_reason: FinishReason::Length, + kv_transfer_params: None, + }), + }), + ]); + + let chunks = completion_chunk_stream( + stream, + "cmpl-1".to_string(), + "model".to_string(), + 1, + ApiServerOptions::default(), + ResponseOptions { + include_usage: true, + prompt_only: true, + echo: Some("hello".to_string()), + return_token_ids: true, + ..Default::default() + }, + ) + .collect::>() + .await; + + let chunks: Vec<_> = chunks.into_iter().try_collect().expect("stream should succeed"); + assert_eq!(chunks.len(), 3); + + match &chunks[0] { + CompletionSseChunk::Chunk(chunk) => { + assert_eq!(chunk.choices[0].text, "hello"); + assert_eq!( + chunk.choices[0].prompt_token_ids.as_deref(), + Some(&[1, 2][..]) + ); + } + CompletionSseChunk::Usage(_) => panic!("expected prompt chunk"), + } + match &chunks[1] { + CompletionSseChunk::Chunk(chunk) => { + assert_eq!(chunk.choices[0].text, ""); + assert_eq!(chunk.choices[0].finish_reason.as_deref(), Some("length")); + } + CompletionSseChunk::Usage(_) => panic!("expected final chunk"), + } + match &chunks[2] { + CompletionSseChunk::Usage(chunk) => { + let usage = chunk.usage.as_ref().expect("usage"); + assert_eq!(usage.prompt_tokens, 2); + assert_eq!(usage.completion_tokens, Some(1)); + assert_eq!(usage.total_tokens, 3); + } + CompletionSseChunk::Chunk(_) => panic!("expected usage chunk"), + } + } + + #[tokio::test] + async fn completion_chunk_stream_maps_prompt_logprobs_for_single_token_prompt() { + let stream = stream::iter(vec![ + Ok(DecodedTextEvent::Start { + prompt_token_ids: vec![9707].into(), + prompt_logprobs: None, + }), + Ok(DecodedTextEvent::TextDelta { + delta: " leaked".to_string(), + token_ids: vec![3], + logprobs: None, + finished: Some(Finished { + usage: vllm_llm::TokenUsage { + prompt_token_count: 1, + output_token_count: 1, + cached_token_count: 0, + }, + finish_reason: FinishReason::Length, + kv_transfer_params: None, + }), + }), + ]); + + let chunks = completion_chunk_stream( + stream, + "cmpl-1".to_string(), + "model".to_string(), + 1, + ApiServerOptions::default(), + ResponseOptions { + prompt_only: true, + echo: Some("Hello".to_string()), + requested_logprobs: Some(1), + ..Default::default() + }, + ) + .collect::>() + .await; + + let chunks: Vec<_> = chunks.into_iter().try_collect().expect("stream should succeed"); + assert_eq!(chunks.len(), 2); + + match &chunks[0] { + CompletionSseChunk::Chunk(chunk) => { + assert_eq!(chunk.choices[0].text, "Hello"); + let logprobs = chunk.choices[0].logprobs.as_ref().expect("logprobs"); + assert_eq!(logprobs.tokens, vec!["Hello".to_string()]); + assert_eq!(logprobs.token_logprobs, vec![None]); + assert_eq!(logprobs.top_logprobs, vec![None]); + assert_eq!(logprobs.text_offset, vec![0]); + } + CompletionSseChunk::Usage(_) => panic!("expected prompt chunk"), + } + match &chunks[1] { + CompletionSseChunk::Chunk(chunk) => { + assert_eq!(chunk.choices[0].text, ""); + assert_eq!(chunk.choices[0].finish_reason.as_deref(), Some("length")); + } + CompletionSseChunk::Usage(_) => panic!("expected final chunk"), + } + } + + #[tokio::test] + async fn completion_chunk_stream_maps_prompt_only_logprobs() { + let stream = stream::iter(vec![ + Ok(DecodedTextEvent::Start { + prompt_token_ids: vec![1, 2].into(), + prompt_logprobs: Some(DecodedPromptLogprobs { + first_token_id: 1, + first_token: "he".to_string(), + scored_positions: vec![DecodedPositionLogprobs { + entries: vec![DecodedTokenLogprob { + token_id: 2, + token: "llo".to_string(), + logprob: -0.2, + rank: 1, + }], + }], + }), + }), + Ok(DecodedTextEvent::TextDelta { + delta: " leaked".to_string(), + token_ids: vec![3], + logprobs: None, + finished: Some(Finished { + usage: vllm_llm::TokenUsage { + prompt_token_count: 2, + output_token_count: 1, + cached_token_count: 0, + }, + finish_reason: FinishReason::Length, + kv_transfer_params: None, + }), + }), + ]); + + let chunks = completion_chunk_stream( + stream, + "cmpl-1".to_string(), + "model".to_string(), + 1, + ApiServerOptions::default(), + ResponseOptions { + prompt_only: true, + echo: Some("hello".to_string()), + requested_logprobs: Some(1), + ..Default::default() + }, + ) + .collect::>() + .await; + + let chunks: Vec<_> = chunks.into_iter().try_collect().expect("stream should succeed"); + assert_eq!(chunks.len(), 2); + + match &chunks[0] { + CompletionSseChunk::Chunk(chunk) => { + assert_eq!(chunk.choices[0].text, "hello"); + let logprobs = chunk.choices[0].logprobs.as_ref().expect("logprobs"); + assert_eq!(logprobs.tokens, vec!["he".to_string(), "llo".to_string()]); + assert_eq!(logprobs.token_logprobs, vec![None, Some(-0.2)]); + assert_eq!(logprobs.text_offset, vec![0, 2]); + } + CompletionSseChunk::Usage(_) => panic!("expected prompt chunk"), + } + match &chunks[1] { + CompletionSseChunk::Chunk(chunk) => { + assert_eq!(chunk.choices[0].text, ""); + assert_eq!(chunk.choices[0].finish_reason.as_deref(), Some("length")); + } + CompletionSseChunk::Usage(_) => panic!("expected final chunk"), + } + } } diff --git a/rust/src/server/src/routes/openai/completions/convert.rs b/rust/src/server/src/routes/openai/completions/convert.rs index 2f6c760a9903..9c3069285901 100644 --- a/rust/src/server/src/routes/openai/completions/convert.rs +++ b/rust/src/server/src/routes/openai/completions/convert.rs @@ -27,6 +27,8 @@ pub(super) struct ResponseOptions { pub include_usage: bool, /// Whether every streamed chunk should carry cumulative usage. pub include_continuous_usage: bool, + /// Whether the caller requested prompt-only echo via `max_tokens=0`. + pub prompt_only: bool, /// Original text prompt that should be echoed back northbound when /// `echo=true`. pub echo: Option, @@ -68,11 +70,13 @@ pub(super) fn prepare_completion_request( })?), None => None, }; - let prompt_logprobs = request.prompt_logprobs.or(if request.echo && !request.stream { - logprobs - } else { - None - }); + let prompt_only = request.echo && request.max_tokens == Some(0); + let prompt_logprobs = + request.prompt_logprobs.or(if request.echo && (!request.stream || prompt_only) { + logprobs + } else { + None + }); let include_usage = (request.stream_options.as_ref()) .and_then(|options| options.include_usage) .unwrap_or(false); @@ -83,6 +87,11 @@ pub(super) fn prepare_completion_request( .and_then(|options| options.continuous_usage_stats) .unwrap_or(false); let include_prompt_logprobs = prompt_logprobs.is_some(); + let max_tokens = if prompt_only { + Some(1) + } else { + request.max_tokens + }; let echo = request.echo.then(|| request.prompt.as_text().cloned()).flatten(); let structured_outputs = @@ -97,7 +106,7 @@ pub(super) fn prepare_completion_request( top_p: request.top_p, top_k: request.top_k, seed: request.seed, - max_tokens: request.max_tokens, + max_tokens, min_tokens: request.min_tokens, logprobs, prompt_logprobs, @@ -138,6 +147,7 @@ pub(super) fn prepare_completion_request( options: ResponseOptions { include_usage, include_continuous_usage, + prompt_only, echo, requested_logprobs: request.logprobs, include_prompt_logprobs, @@ -325,6 +335,57 @@ mod tests { assert_eq!(prepared.options.echo, Some("hello".to_string())); assert_eq!(prepared.text_request.sampling_params.max_tokens, Some(7)); + assert!(!prepared.options.prompt_only); + } + + #[test] + fn prepare_completion_request_lowers_prompt_only_echo_as_one_internal_token() { + let request: CompletionRequest = serde_json::from_value(json!({ + "model": "Qwen/Qwen1.5-0.5B-Chat", + "prompt": "hello", + "stream": false, + "echo": true, + "max_tokens": 0 + })) + .expect("parse request"); + + let prepared = prepare_completion_request( + request, + &served(&["Qwen/Qwen1.5-0.5B-Chat"]), + ResolvedRequestContext::default(), + ) + .expect("prepare"); + + assert!(prepared.options.prompt_only); + assert_eq!(prepared.options.echo, Some("hello".to_string())); + assert_eq!(prepared.text_request.sampling_params.max_tokens, Some(1)); + } + + #[test] + fn prepare_completion_request_enables_prompt_logprobs_for_stream_prompt_only_echo() { + let request: CompletionRequest = serde_json::from_value(json!({ + "model": "Qwen/Qwen1.5-0.5B-Chat", + "prompt": "hello", + "echo": true, + "stream": true, + "max_tokens": 0, + "logprobs": 3 + })) + .expect("parse request"); + + let prepared = prepare_completion_request( + request, + &served(&["Qwen/Qwen1.5-0.5B-Chat"]), + ResolvedRequestContext::default(), + ) + .expect("prepare"); + + assert!(prepared.options.prompt_only); + assert_eq!(prepared.text_request.sampling_params.logprobs, Some(3)); + assert_eq!( + prepared.text_request.sampling_params.prompt_logprobs, + Some(3) + ); } #[test] diff --git a/rust/src/server/src/routes/openai/completions/validate.rs b/rust/src/server/src/routes/openai/completions/validate.rs index 2af41877bfd5..cbb040b90d0f 100644 --- a/rust/src/server/src/routes/openai/completions/validate.rs +++ b/rust/src/server/src/routes/openai/completions/validate.rs @@ -2,9 +2,6 @@ use vllm_text::Prompt; use super::types::CompletionRequest; use crate::error::{ApiError, bail_invalid_request}; -use crate::routes::openai::utils::token_ids::{ - validate_allowed_token_ids, validate_logit_bias, validate_prompt_token_ids, -}; /// Enforce the minimal compatibility contract for the Rust OpenAI server. pub(super) fn validate_request_compat( @@ -29,8 +26,11 @@ pub(super) fn validate_request_compat( bail_invalid_request!(param = "n", "Only n=1 is supported."); } - if request.max_tokens == Some(0) { - bail_invalid_request!(param = "max_tokens", "max_tokens must be greater than 0."); + if request.max_tokens == Some(0) && !request.echo { + bail_invalid_request!( + param = "max_tokens", + "max_tokens=0 is only supported when echo=true." + ); } if request.echo && matches!(request.prompt, Prompt::TokenIds(_)) { @@ -98,63 +98,13 @@ pub(super) fn validate_request_compat( Ok(()) } -/// Reject out-of-vocab token ids, mirroring the Python input processor. A token-id -/// prompt may reference ids the engine embeds beyond either vocab alone (Qwen3 -/// extra LM tokens, multimodal placeholders), so it is bounded by the union of the -/// tokenizer and model vocabularies; `allowed_token_ids` by the tokenizer vocab; -/// `logit_bias` keys by the model vocab (skipped when the model size is unknown). -pub(super) fn validate_token_id_ranges( - request: &CompletionRequest, - tokenizer_vocab_size: usize, - model_vocab_size: Option, -) -> Result<(), ApiError> { - let prompt_bound = tokenizer_vocab_size.max(model_vocab_size.unwrap_or(0)); - validate_prompt_token_ids(&request.prompt, prompt_bound)?; - validate_allowed_token_ids(request.allowed_token_ids.as_deref(), tokenizer_vocab_size)?; - validate_logit_bias( - request.logit_bias.as_ref(), - model_vocab_size.unwrap_or(usize::MAX), - ) -} - #[cfg(test)] mod tests { use serde_json::json; - use vllm_text::Prompt; - use super::{validate_request_compat, validate_token_id_ranges}; + use super::validate_request_compat; use crate::routes::openai::completions::types::CompletionRequest; - #[test] - fn validate_token_id_ranges_rejects_oob_prompt_and_params() { - // a token-id prompt below both vocabs is accepted (the engine can embed it) - let mut request = base_request(); - request.prompt = Prompt::TokenIds(vec![5, 150]); - assert!(validate_token_id_ranges(&request, 100, Some(200)).is_ok()); - // an id at or above the union of the two vocabs is rejected - let mut request = base_request(); - request.prompt = Prompt::TokenIds(vec![5, 200]); - assert!(validate_token_id_ranges(&request, 100, Some(200)).is_err()); - // an id beyond the model vocab but within the (larger) tokenizer vocab is - // accepted: the engine embeds added/placeholder ids above the model vocab, - // matching the Python input processor's max(tokenizer, model) bound - let mut request = base_request(); - request.prompt = Prompt::TokenIds(vec![150]); - assert!(validate_token_id_ranges(&request, 200, Some(100)).is_ok()); - // falls back to the tokenizer vocab when the model size is unknown - let mut request = base_request(); - request.prompt = Prompt::TokenIds(vec![150]); - assert!(validate_token_id_ranges(&request, 100, None).is_err()); - // allowed_token_ids are bounded by the tokenizer vocab -> reject - let mut request = base_request(); - request.allowed_token_ids = Some(vec![150]); - assert!(validate_token_id_ranges(&request, 100, Some(200)).is_err()); - // unknown sizes -> skip - let mut request = base_request(); - request.prompt = Prompt::TokenIds(vec![1_000_000]); - assert!(validate_token_id_ranges(&request, usize::MAX, None).is_ok()); - } - fn base_request() -> CompletionRequest { serde_json::from_value(json!({ "model": "Qwen/Qwen1.5-0.5B-Chat", @@ -219,4 +169,30 @@ mod tests { validate_request_compat(&request, &served_names(&["Qwen/Qwen1.5-0.5B-Chat"])).is_ok() ); } + + #[test] + fn validate_request_compat_accepts_prompt_only_echo() { + let request = CompletionRequest { + stream: false, + echo: true, + max_tokens: Some(0), + ..base_request() + }; + assert!( + validate_request_compat(&request, &served_names(&["Qwen/Qwen1.5-0.5B-Chat"])).is_ok() + ); + } + + #[test] + fn validate_request_compat_rejects_prompt_only_without_echo() { + let request = CompletionRequest { + stream: false, + echo: false, + max_tokens: Some(0), + ..base_request() + }; + assert!( + validate_request_compat(&request, &served_names(&["Qwen/Qwen1.5-0.5B-Chat"])).is_err() + ); + } } diff --git a/rust/src/server/src/routes/openai/utils/mod.rs b/rust/src/server/src/routes/openai/utils/mod.rs index 7ec1251ddf30..70e9d1466ded 100644 --- a/rust/src/server/src/routes/openai/utils/mod.rs +++ b/rust/src/server/src/routes/openai/utils/mod.rs @@ -1,6 +1,5 @@ pub mod logprobs; pub mod structured_outputs; -pub mod token_ids; pub mod types; pub mod usage; pub mod validated_json; diff --git a/rust/src/server/src/routes/openai/utils/token_ids.rs b/rust/src/server/src/routes/openai/utils/token_ids.rs deleted file mode 100644 index ffa945ef9478..000000000000 --- a/rust/src/server/src/routes/openai/utils/token_ids.rs +++ /dev/null @@ -1,55 +0,0 @@ -use std::collections::HashMap; - -use vllm_text::Prompt; - -use crate::error::{ApiError, bail_invalid_request}; - -/// Reject token-id prompt entries at or above `bound` (the highest in-vocab id is -/// `bound - 1`). -pub(crate) fn validate_prompt_token_ids(prompt: &Prompt, bound: usize) -> Result<(), ApiError> { - if let Prompt::TokenIds(ids) = prompt - && let Some(&bad) = ids.iter().find(|&&id| id as usize >= bound) - { - bail_invalid_request!( - param = "prompt", - "prompt contains out-of-vocab token id {bad}; vocabulary size is {bound}." - ); - } - Ok(()) -} - -/// Reject `allowed_token_ids` entries at or above `bound`. -pub(crate) fn validate_allowed_token_ids( - allowed_token_ids: Option<&[u32]>, - bound: usize, -) -> Result<(), ApiError> { - if let Some(ids) = allowed_token_ids - && let Some(&bad) = ids.iter().find(|&&id| id as usize >= bound) - { - bail_invalid_request!( - param = "allowed_token_ids", - "allowed_token_ids contains out-of-vocab token id {bad}; vocabulary size is {bound}." - ); - } - Ok(()) -} - -/// Reject `logit_bias` keys at or above `bound`. -pub(crate) fn validate_logit_bias( - logit_bias: Option<&HashMap>, - bound: usize, -) -> Result<(), ApiError> { - if let Some(bias) = logit_bias { - for key in bias.keys() { - if let Ok(id) = key.parse::() - && id as usize >= bound - { - bail_invalid_request!( - param = "logit_bias", - "logit_bias contains out-of-vocab token id {id}; vocabulary size is {bound}." - ); - } - } - } - Ok(()) -} diff --git a/rust/src/server/src/routes/tests.rs b/rust/src/server/src/routes/tests.rs index c6de40340265..5eb65a498533 100644 --- a/rust/src/server/src/routes/tests.rs +++ b/rust/src/server/src/routes/tests.rs @@ -43,7 +43,7 @@ use zeromq::prelude::{SocketRecv, SocketSend}; use zeromq::{DealerSocket, PushSocket, ZmqMessage}; use super::{build_router, build_router_with_dev_mode, build_router_with_dev_mode_and_lora}; -use crate::config::ApiServerOptions; +use crate::config::{ApiServerOptions, CorsConfig}; use crate::state::AppState; fn request_output( @@ -819,6 +819,35 @@ async fn test_app_with_api_keys(api_keys: Vec) -> (axum::Router, MockEng (app, engine_task) } +async fn test_app_with_cors_and_keys( + cors: CorsConfig, + api_keys: Vec, +) -> (axum::Router, MockEngineTask) { + let (chat, engine_task) = test_models_with_engine_outputs_and_backend( + b"engine-openai-cors", + default_stream_output_specs(), + Arc::new(FakeChatBackend::new()), + ) + .await; + let app = build_router(Arc::new( + AppState::new(vec!["Qwen/Qwen1.5-0.5B-Chat".to_string()], chat) + .with_cors(cors) + .with_api_keys(api_keys), + )); + (app, engine_task) +} + +async fn test_app_with_cors(cors: CorsConfig) -> (axum::Router, MockEngineTask) { + test_app_with_cors_and_keys(cors, vec![]).await +} + +fn header_value<'a>(response: &'a axum::response::Response, name: &str) -> Option<&'a str> { + response + .headers() + .get(name) + .map(|value| value.to_str().expect("header is valid utf-8")) +} + async fn test_health_app_with_engine_script( script: F, ) -> (axum::Router, Arc, MockEngineTask) @@ -1212,6 +1241,273 @@ async fn api_key_auth_allows_unguarded_route_without_token() { assert_eq!(response.status(), StatusCode::OK); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn cors_default_simple_request_allows_any_origin() { + let (mut app, _engine_task) = test_app_with_cors(CorsConfig::default()).await; + let response = app + .call( + Request::builder() + .method("GET") + .uri("/v1/models") + .header("origin", "http://example.com") + .body(Body::empty()) + .expect("build request"), + ) + .await + .expect("call app"); + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + header_value(&response, "access-control-allow-origin"), + Some("*") + ); + // Wildcard origins without credentials emit no `Vary` (Starlette parity). + assert_eq!(header_value(&response, "vary"), None); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn cors_default_preflight_returns_explicit_methods_and_max_age() { + let (mut app, _engine_task) = test_app_with_cors(CorsConfig::default()).await; + let response = app + .call( + Request::builder() + .method("OPTIONS") + .uri("/v1/chat/completions") + .header("origin", "http://example.com") + .header("access-control-request-method", "POST") + .header("access-control-request-headers", "content-type") + .body(Body::empty()) + .expect("build request"), + ) + .await + .expect("call app"); + + assert_eq!(response.status(), StatusCode::OK); + // `*` methods expand to the explicit method list, matching Starlette + // (never the literal `*`). + assert_eq!( + header_value(&response, "access-control-allow-methods"), + Some("DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT") + ); + assert_eq!( + header_value(&response, "access-control-max-age"), + Some("600") + ); + // `*` headers mirror the requested headers. + assert_eq!( + header_value(&response, "access-control-allow-headers"), + Some("content-type") + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn cors_no_origin_request_has_no_cors_headers() { + let (mut app, _engine_task) = test_app_with_cors(CorsConfig::default()).await; + let response = app + .call( + Request::builder() + .method("GET") + .uri("/health") + .body(Body::empty()) + .expect("build request"), + ) + .await + .expect("call app"); + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(header_value(&response, "access-control-allow-origin"), None); + assert_eq!(header_value(&response, "vary"), None); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn cors_explicit_origin_allowed_reflects_origin_with_vary() { + let cors = CorsConfig { + allow_origins: vec!["http://allowed.com".to_string()], + ..CorsConfig::default() + }; + let (mut app, _engine_task) = test_app_with_cors(cors).await; + let response = app + .call( + Request::builder() + .method("GET") + .uri("/v1/models") + .header("origin", "http://allowed.com") + .body(Body::empty()) + .expect("build request"), + ) + .await + .expect("call app"); + + assert_eq!( + header_value(&response, "access-control-allow-origin"), + Some("http://allowed.com") + ); + assert_eq!(header_value(&response, "vary"), Some("origin")); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn cors_explicit_origin_disallowed_omits_allow_origin() { + let cors = CorsConfig { + allow_origins: vec!["http://allowed.com".to_string()], + ..CorsConfig::default() + }; + let (mut app, _engine_task) = test_app_with_cors(cors).await; + let response = app + .call( + Request::builder() + .method("GET") + .uri("/v1/models") + .header("origin", "http://evil.com") + .body(Body::empty()) + .expect("build request"), + ) + .await + .expect("call app"); + + assert_eq!(header_value(&response, "access-control-allow-origin"), None); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn cors_wildcard_with_credentials_reflects_origin_without_panic() { + let cors = CorsConfig { + allow_credentials: true, + ..CorsConfig::default() + }; + let (mut app, _engine_task) = test_app_with_cors(cors).await; + let response = app + .call( + Request::builder() + .method("GET") + .uri("/v1/models") + .header("origin", "http://example.com") + .body(Body::empty()) + .expect("build request"), + ) + .await + .expect("call app"); + + // `*` + credentials reflects the request origin instead of `*` (Starlette + // parity, and avoids tower-http's wildcard+credentials panic). + assert_eq!( + header_value(&response, "access-control-allow-origin"), + Some("http://example.com") + ); + assert_eq!( + header_value(&response, "access-control-allow-credentials"), + Some("true") + ); + assert_eq!(header_value(&response, "vary"), Some("origin")); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn cors_unauthorized_response_has_no_cors_headers() { + let (mut app, _engine_task) = + test_app_with_cors_and_keys(CorsConfig::default(), vec!["secret".to_string()]).await; + let response = app + .call( + Request::builder() + .method("GET") + .uri("/v1/models") + .header("origin", "http://example.com") + .body(Body::empty()) + .expect("build request"), + ) + .await + .expect("call app"); + + // Auth sits outside CORS, so a 401 carries no CORS headers. + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); + assert_eq!(header_value(&response, "access-control-allow-origin"), None); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn cors_preflight_bypasses_auth_and_returns_cors_headers() { + let (mut app, _engine_task) = + test_app_with_cors_and_keys(CorsConfig::default(), vec!["secret".to_string()]).await; + let response = app + .call( + Request::builder() + .method("OPTIONS") + .uri("/v1/chat/completions") + .header("origin", "http://example.com") + .header("access-control-request-method", "POST") + .body(Body::empty()) + .expect("build request"), + ) + .await + .expect("call app"); + + assert_ne!(response.status(), StatusCode::UNAUTHORIZED); + assert_eq!( + header_value(&response, "access-control-allow-origin"), + Some("*") + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn cors_explicit_methods_preflight_returns_that_list() { + let cors = CorsConfig { + allow_methods: vec!["GET".to_string(), "POST".to_string()], + ..CorsConfig::default() + }; + let (mut app, _engine_task) = test_app_with_cors(cors).await; + let response = app + .call( + Request::builder() + .method("OPTIONS") + .uri("/v1/chat/completions") + .header("origin", "http://example.com") + .header("access-control-request-method", "POST") + .body(Body::empty()) + .expect("build request"), + ) + .await + .expect("call app"); + + // Explicit methods are emitted verbatim, not expanded and not `*`. + assert_eq!( + header_value(&response, "access-control-allow-methods"), + Some("GET,POST") + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn cors_explicit_headers_union_safelisted_headers() { + let cors = CorsConfig { + allow_headers: vec!["X-Custom".to_string()], + ..CorsConfig::default() + }; + let (mut app, _engine_task) = test_app_with_cors(cors).await; + let response = app + .call( + Request::builder() + .method("OPTIONS") + .uri("/v1/chat/completions") + .header("origin", "http://example.com") + .header("access-control-request-method", "POST") + .body(Body::empty()) + .expect("build request"), + ) + .await + .expect("call app"); + + // Explicit headers are unioned with the safelisted set, lowercased + sorted. + assert_eq!( + header_value(&response, "access-control-allow-headers"), + Some("accept,accept-language,content-language,content-type,x-custom") + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[serial] async fn version_returns_engine_vllm_version() { @@ -1677,6 +1973,85 @@ async fn http_metrics_record_list_models_requests() { ); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn request_metrics_use_served_model_name_label() { + let ipc = IpcNamespace::new().expect("create ipc namespace"); + let handshake_address = ipc.handshake_endpoint(); + let engine_id = b"engine-openai-served-model-metrics".to_vec(); + + let engine_task = MockEngineTask::new(spawn_mock_engine_task( + handshake_address.clone(), + engine_id.clone(), + |dealer, push| { + boxed_test_future(async move { + let add = recv_engine_message(dealer).await; + let request: EngineCoreRequest = + rmp_serde::from_slice(&add[1]).expect("decode request"); + send_outputs( + push, + engine_outputs_for_request(&request.request_id, default_stream_output_specs()), + ) + .await; + }) + }, + )); + + let client = EngineCoreClient::connect( + EngineCoreClientConfig::new_single(handshake_address) + .with_model_name("served-model-metrics") + .with_local_input_output_addresses( + Some(ipc.input_endpoint()), + Some(ipc.output_endpoint()), + ), + ) + .await + .expect("connect client"); + let chat = ChatLlm::from_shared_backend(test_llm(client), Arc::new(FakeChatBackend::new())); + let mut app = build_router(Arc::new(AppState::new( + vec![ + "served-model-metrics".to_string(), + "served-model-alias".to_string(), + ], + chat, + ))); + let before = METRICS.render().unwrap(); + + let response = app + .call( + Request::builder() + .method("POST") + .uri("/v1/chat/completions") + .header("content-type", "application/json") + .body(Body::from( + json!({ + "model": "served-model-alias", + "stream": false, + "messages": [{"role": "user", "content": "hello"}] + }) + .to_string(), + )) + .expect("build request"), + ) + .await + .expect("call app"); + + assert_eq!(response.status(), StatusCode::OK); + let _ = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + + let after = METRICS.render().unwrap(); + assert_eq!( + metric_delta( + &before, + &after, + "vllm:request_success_total", + Some("model_name=\"served-model-metrics\",engine=\"0\",finished_reason=\"stop\""), + ), + 1.0 + ); + engine_task.await.expect("mock engine task"); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[serial] async fn wrong_model_returns_not_found() { @@ -4546,6 +4921,111 @@ async fn is_paused_route_returns_json_payload() { ); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn abort_requests_route_returns_ok_for_well_formed_body() { + let (app, engine_task) = + test_admin_app_with_engine_script(|_dealer, _push| boxed_test_future(async move {})).await; + + let response = app + .clone() + .call( + Request::builder() + .method("POST") + .uri("/abort_requests") + .header("content-type", "application/json") + .body(Body::from(r#"{"request_ids":["req-1","req-2"]}"#)) + .expect("build request"), + ) + .await + .expect("call app"); + + let status = response.status(); + let body = to_bytes(response.into_body(), usize::MAX).await.expect("read body"); + assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body)); + assert!(body.is_empty()); + engine_task.abort_and_join().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn abort_requests_route_rejects_missing_request_ids() { + let (app, engine_task) = + test_admin_app_with_engine_script(|_dealer, _push| boxed_test_future(async move {})).await; + + let response = app + .clone() + .call( + Request::builder() + .method("POST") + .uri("/abort_requests") + .header("content-type", "application/json") + .body(Body::from(r#"{}"#)) + .expect("build request"), + ) + .await + .expect("call app"); + + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let body = to_bytes(response.into_body(), usize::MAX).await.expect("read body"); + let json: serde_json::Value = serde_json::from_slice(&body).expect("decode json"); + assert_eq!(json["error"]["type"], "invalid_request_error"); + assert_eq!(json["error"]["param"], "request_ids"); + engine_task.abort_and_join().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn abort_requests_route_rejects_malformed_json() { + let (app, engine_task) = + test_admin_app_with_engine_script(|_dealer, _push| boxed_test_future(async move {})).await; + + let response = app + .clone() + .call( + Request::builder() + .method("POST") + .uri("/abort_requests") + .header("content-type", "application/json") + .body(Body::from(r#"{"request_ids": "#)) + .expect("build request"), + ) + .await + .expect("call app"); + + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let body = to_bytes(response.into_body(), usize::MAX).await.expect("read body"); + let json: serde_json::Value = serde_json::from_slice(&body).expect("decode json"); + assert_eq!(json["error"]["type"], "invalid_request_error"); + engine_task.abort_and_join().await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial] +async fn abort_requests_route_accepts_empty_id_list() { + let (app, engine_task) = + test_admin_app_with_engine_script(|_dealer, _push| boxed_test_future(async move {})).await; + + let response = app + .clone() + .call( + Request::builder() + .method("POST") + .uri("/abort_requests") + .header("content-type", "application/json") + .body(Body::from(r#"{"request_ids":[]}"#)) + .expect("build request"), + ) + .await + .expect("call app"); + + let status = response.status(); + let body = to_bytes(response.into_body(), usize::MAX).await.expect("read body"); + assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&body)); + assert!(body.is_empty()); + engine_task.abort_and_join().await; +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[serial] async fn admin_routes_are_hidden_when_dev_mode_is_disabled() { @@ -4566,6 +5046,7 @@ async fn admin_routes_are_hidden_when_dev_mode_is_disabled() { ("POST", "/pause"), ("POST", "/resume"), ("POST", "/collective_rpc"), + ("POST", "/abort_requests"), ("POST", "/reset_prefix_cache"), ("POST", "/reset_mm_cache"), ("POST", "/reset_encoder_cache"), diff --git a/rust/src/server/src/routes/tokenize/types.rs b/rust/src/server/src/routes/tokenize/types.rs index 9a5977b31800..987e0e23f396 100644 --- a/rust/src/server/src/routes/tokenize/types.rs +++ b/rust/src/server/src/routes/tokenize/types.rs @@ -83,6 +83,7 @@ impl TokenizeChatRequest { }, tools: convert_tools(self.tools)?, tool_choice: ChatToolChoice::Auto, + parallel_tool_calls: true, decode_options: TextDecodeOptions::default(), intermediate: false, priority: 0, diff --git a/rust/src/server/src/state.rs b/rust/src/server/src/state.rs index 55959b60d935..0be074dff88c 100644 --- a/rust/src/server/src/state.rs +++ b/rust/src/server/src/state.rs @@ -9,7 +9,7 @@ use vllm_chat::ChatLlm; use vllm_engine_core_client::EngineCoreClient; use vllm_engine_core_client::protocol::lora::LoraRequest; -use crate::config::ApiServerOptions; +use crate::config::{ApiServerOptions, CorsConfig}; use crate::lora::{LoadLoraError, LoraManager, LoraModelResolution, UnloadLoraError}; use crate::server_info::{ServerInfoConfigFormat, ServerInfoSnapshot}; @@ -30,6 +30,8 @@ pub struct AppState { pub chat: ChatLlm, /// HTTP/API-server behavior switches. pub api_server_options: ApiServerOptions, + /// CORS settings applied to every HTTP response. + pub cors: CorsConfig, /// Runtime server information returned by `/server_info`, when available. server_info: Option, /// SHA-256 hashes of API keys accepted as bearer tokens for guarded routes. @@ -58,6 +60,7 @@ impl AppState { served_model_names, chat, api_server_options: ApiServerOptions::default(), + cors: CorsConfig::default(), server_info: None, api_key_hashes: Vec::new(), server_load: AtomicU64::new(0), @@ -71,6 +74,12 @@ impl AppState { self } + /// Set the CORS settings applied to every HTTP response. + pub fn with_cors(mut self, cors: CorsConfig) -> Self { + self.cors = cors; + self + } + /// Attach the runtime server information snapshot used by `/server_info`. pub(crate) fn with_server_info(mut self, server_info: ServerInfoSnapshot) -> Self { self.server_info = Some(server_info); @@ -114,16 +123,6 @@ impl AppState { &self.served_model_names } - /// Tokenizer vocabulary size. - pub fn tokenizer_vocab_size(&self) -> usize { - self.chat.tokenizer_vocab_size() - } - - /// Model vocabulary size, else `None`. - pub fn model_vocab_size(&self) -> Option { - self.chat.model_vocab_size() - } - /// Return base served model names plus dynamically loaded LoRA adapter /// names. pub async fn served_model_names_with_loras(&self) -> Vec { diff --git a/rust/src/text/src/backend/hf/config.rs b/rust/src/text/src/backend/hf/config.rs index 1efb31618d1e..fbf796b5a7fb 100644 --- a/rust/src/text/src/backend/hf/config.rs +++ b/rust/src/text/src/backend/hf/config.rs @@ -91,9 +91,7 @@ impl HfSpecialTokens { #[serde(default)] pub struct ModelConfig { model_type: Option, - max_position_embeddings: Option, vocab_size: Option, - num_attention_heads: Option, num_experts: Option, moe_num_experts: Option, n_routed_experts: Option, @@ -180,29 +178,18 @@ impl ModelConfig { self.model_type.as_deref().or_else(|| self.text_config.as_deref()?.model_type()) } - /// Return the effective model vocabulary size, following the same simplified - /// text-config selection as `model_type`: the top-level config wins, - /// otherwise a single nested `text_config` may provide it. - pub fn vocab_size(&self) -> Option { - self.vocab_size.or_else(|| self.text_config.as_deref()?.vocab_size()) - } - - /// Reject partially nested `text_config` payloads that are unlikely to be - /// valid LLM configs for our current use. - /// - /// This keeps the simplified Rust-side parsing honest: if a model declares - /// `text_config`, it must at least look like a real text model config. - fn validate_text_config_selection(&self) -> Result<()> { - if let Some(text_config) = self.text_config.as_deref() - && text_config.num_attention_heads.is_none() - { - return Err(Error::Tokenizer( - "the text config extracted from the model config does not have `num_attention_heads`" - .to_string(), - )); + /// Return the effective model vocabulary size, following the same + /// simplified text-config selection as `model_type`. + pub fn vocab_size(&self) -> Result { + if let Some(vocab_size) = self.vocab_size { + Ok(vocab_size) + } else if let Some(text_config) = self.text_config.as_deref() { + text_config.vocab_size() + } else { + Err(Error::Tokenizer( + "the model config does not define `vocab_size`".to_string(), + )) } - - Ok(()) } /// Match Python's current expert-count priority on the selected text @@ -245,10 +232,6 @@ impl ModelConfig { pub(super) fn is_moe(&self) -> bool { self.num_experts() > 0 } - - pub(super) fn max_position_embeddings(&self) -> Option { - self.effective_text_config().max_position_embeddings - } } /// Load the tokenizer-side EOS metadata if a config file is present. @@ -263,9 +246,7 @@ pub(super) fn load_generation_config(path: Option<&Path>) -> Result) -> Result { - let config: ModelConfig = read_json_file(path)?; - config.validate_text_config_selection()?; - Ok(config) + read_json_file(path) } fn read_json_file(path: Option<&Path>) -> Result @@ -343,12 +324,9 @@ mod tests { r#"{ "model_type": "top_level", "num_experts": 64, - "max_position_embeddings": 8192, "text_config": { "model_type": "nested", - "num_attention_heads": 32, - "num_local_experts": 8, - "max_position_embeddings": 4096 + "num_local_experts": 8 } }"#, ) @@ -356,26 +334,36 @@ mod tests { assert_eq!(config.num_experts(), 8); assert_eq!(config.model_type(), Some("top_level")); - assert_eq!(config.max_position_embeddings(), Some(4096)); assert!(config.is_moe()); } #[test] - fn model_config_defaults_to_non_moe_when_no_expert_metadata_exists() { - let config: ModelConfig = - serde_json::from_str(r#"{"max_position_embeddings":4096}"#).unwrap(); + fn model_config_uses_nested_vocab_size_when_top_level_is_absent() { + let config: ModelConfig = serde_json::from_str( + r#"{ + "text_config": { + "vocab_size": 151936 + } + }"#, + ) + .unwrap(); - assert_eq!(config.num_experts(), 0); - assert!(!config.is_moe()); - assert_eq!(config.max_position_embeddings(), Some(4096)); + assert_eq!(config.vocab_size().unwrap(), 151936); + } + + #[test] + fn model_config_rejects_missing_vocab_size() { + let config: ModelConfig = serde_json::from_str(r#"{}"#).unwrap(); + + let error = config.vocab_size().unwrap_err(); + assert!(error.to_string().contains("does not define `vocab_size`")); } #[test] - fn model_config_rejects_nested_text_config_without_attention_heads() { - let config: ModelConfig = - serde_json::from_str(r#"{"text_config":{"max_position_embeddings":4096}}"#).unwrap(); + fn model_config_defaults_to_non_moe_when_no_expert_metadata_exists() { + let config: ModelConfig = serde_json::from_str(r#"{}"#).unwrap(); - let error = config.validate_text_config_selection().unwrap_err(); - assert!(error.to_string().contains("does not have `num_attention_heads`"),); + assert_eq!(config.num_experts(), 0); + assert!(!config.is_moe()); } } diff --git a/rust/src/text/src/backend/hf/mod.rs b/rust/src/text/src/backend/hf/mod.rs index b6b79d9914fa..0e8a9bd3c027 100644 --- a/rust/src/text/src/backend/hf/mod.rs +++ b/rust/src/text/src/backend/hf/mod.rs @@ -36,6 +36,8 @@ pub struct HfTextBackend { /// Generation-config for sampling defaults that may be inherited when the /// user does not explicitly override them. generation_config: GenerationConfig, + /// Model vocabulary size from the selected text config. + model_vocab_size: usize, /// Model config (`config.json`). model_config: ModelConfig, } @@ -58,6 +60,7 @@ impl HfTextBackend { .and_then(|token| tokenizer.token_to_id(token.as_str())); let model_config = load_model_config(files.config_path.as_deref())?; + let model_vocab_size = model_config.vocab_size()? as usize; let generation_config = load_generation_config(files.generation_config_path.as_deref())?; let mut extra_eos_token_ids = generation_config .eos_token_id @@ -80,6 +83,7 @@ impl HfTextBackend { primary_eos_token_id, extra_eos_token_ids, generation_config, + model_vocab_size, model_config, }) } @@ -100,8 +104,8 @@ impl TextBackend for HfTextBackend { self.model_config.is_moe() } - fn model_vocab_size(&self) -> Option { - self.model_config.vocab_size().map(|v| v as usize) + fn model_vocab_size(&self) -> usize { + self.model_vocab_size } fn model_id(&self) -> &str { @@ -118,7 +122,6 @@ impl TextBackend for HfTextBackend { default_min_p: self.generation_config.min_p, default_repetition_penalty: self.generation_config.repetition_penalty, default_max_tokens: self.generation_config.max_new_tokens, - max_model_len: self.model_config.max_position_embeddings(), }) } } diff --git a/rust/src/text/src/backend/mod.rs b/rust/src/text/src/backend/mod.rs index 680d454da9bc..8bc834aeae2c 100644 --- a/rust/src/text/src/backend/mod.rs +++ b/rust/src/text/src/backend/mod.rs @@ -6,8 +6,8 @@ use vllm_tokenizer::DynTokenizer; use crate::error::Result; -/// Tokenizer/model-derived hints used to enrich text-generation requests before -/// they are lowered into engine-core. +/// Tokenizer/model-derived defaults used to enrich text-generation requests +/// before they are lowered into engine-core. #[derive(Debug, Clone, Default, PartialEq)] pub struct SamplingHints { pub primary_eos_token_id: Option, @@ -18,9 +18,38 @@ pub struct SamplingHints { pub default_min_p: Option, pub default_repetition_penalty: Option, pub default_max_tokens: Option, - /// Model context window size (`max_position_embeddings` from - /// `config.json`). - pub max_model_len: Option, +} + +/// Effective bounds used to validate and lower sampling requests. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SamplingLimits { + /// Runtime context window size reported by the engine startup handshake. + pub max_model_len: u32, + /// Maximum number of top log probabilities accepted by this frontend. + /// + /// `-1` means allowing requests up to the model vocabulary size. + pub max_logprobs: i32, + + /// Model vocabulary size from the model config, used to bound generated + /// token IDs and logits-domain sampling controls. + pub model_vocab_size: usize, + /// Tokenizer vocabulary size, used to bound `allowed_token_ids` and + /// token-ID prompts. + pub tokenizer_vocab_size: usize, +} + +impl SamplingLimits { + /// Original Python definition: + /// + pub const DEFAULT_MAX_LOGPROBS: i32 = 20; + /// Original Python definition: + /// + pub const MAX_LOGPROB_TOKEN_IDS: usize = 128; + + /// Return the union bound used to validate token-ID prompts. + pub fn prompt_token_vocab_size(&self) -> usize { + self.tokenizer_vocab_size.max(self.model_vocab_size) + } } /// Minimal text-processing backend needed by `vllm-text`. @@ -42,10 +71,12 @@ pub trait TextBackend: Send + Sync { Ok(SamplingHints::default()) } - /// Return the model vocabulary size from the model config, if known. Used to - /// range-check request token ids against the engine embedding table. - fn model_vocab_size(&self) -> Option { - None + /// Return the model vocabulary size from the model config. + /// + /// The permissive default exists for lightweight test backends. Production + /// backends should override it with the resolved model config value. + fn model_vocab_size(&self) -> usize { + usize::MAX } /// Return the full tokenizer vocabulary size (Python `len(tokenizer)`). diff --git a/rust/src/text/src/error.rs b/rust/src/text/src/error.rs index 62e8e2ae98a5..f686e56d5215 100644 --- a/rust/src/text/src/error.rs +++ b/rust/src/text/src/error.rs @@ -2,6 +2,9 @@ use thiserror::Error; use vllm_engine_core_client::Error as EngineCoreError; use vllm_llm::Error as LlmError; +pub use crate::lower::logprobs::LogprobsError; +pub use crate::lower::token_ids::OutOfVocabError; + #[derive(Debug, Error)] pub enum Error { #[error("tokenizer error: {0}")] @@ -13,6 +16,10 @@ pub enum Error { but the prompt contains {prompt_len} input tokens" )] PromptTooLong { max_model_len: u32, prompt_len: u32 }, + #[error(transparent)] + Logprobs(#[from] LogprobsError), + #[error(transparent)] + OutOfVocab(#[from] OutOfVocabError), #[error("text request stream `{request_id}` closed before terminal output")] StreamClosedBeforeTerminalOutput { request_id: String }, #[error(transparent)] diff --git a/rust/src/text/src/lib.rs b/rust/src/text/src/lib.rs index a550a8afc5be..a4fb86d19c58 100644 --- a/rust/src/text/src/lib.rs +++ b/rust/src/text/src/lib.rs @@ -6,8 +6,8 @@ use std::mem::take; -pub use backend::{DynTextBackend, SamplingHints, TextBackend}; -pub use error::{Error, Result}; +pub use backend::{DynTextBackend, SamplingHints, SamplingLimits, TextBackend}; +pub use error::{Error, LogprobsError, OutOfVocabError, Result}; use futures::Stream; pub use lower::{ PreparedTextRequest, lower_sampling_params, lower_text_request, resolve_max_tokens, @@ -45,33 +45,33 @@ pub struct TextLlm { /// Tokenizer/model metadata backend responsible for prompt encode/decode /// and sampling hints. backend: DynTextBackend, - /// Context window size reported by the engine startup handshake, with - /// optional override from config. + /// Runtime context window size reported by the engine startup handshake. max_model_len: u32, + /// Maximum number of top log probabilities accepted by this text facade. + max_logprobs: i32, } impl TextLlm { /// Create a new text-generation facade from a shared LLM client plus a text /// backend. pub fn new(llm: Llm, backend: DynTextBackend) -> Self { - // Prefer the engine-reported max_model_len because it reflects the - // post-profiling, auto-fitted KV cache limit rather than static - // frontend metadata. + // The engine-reported value reflects the post-profiling, auto-fitted + // KV cache limit used at runtime. let max_model_len = llm.engine_core_client().max_model_len(); Self { llm, backend, max_model_len, + max_logprobs: SamplingLimits::DEFAULT_MAX_LOGPROBS, } } - /// Override the maximum model context length explicitly. - /// - /// This takes priority over both the engine-reported default and any - /// tokenizer/model metadata exposed by the backend. - pub fn with_max_model_len(mut self, max_model_len: u32) -> Self { - self.max_model_len = max_model_len; + /// Override the maximum accepted logprobs count. + pub fn with_max_logprobs(mut self, max_logprobs: Option) -> Self { + if let Some(max_logprobs) = max_logprobs { + self.max_logprobs = max_logprobs; + } self } @@ -97,9 +97,9 @@ impl TextLlm { self.backend.tokenizer_vocab_size() } - /// Model vocabulary size from the model config, used to bound `logit_bias` - /// keys and token-id prompts against the engine embedding table. - pub fn model_vocab_size(&self) -> Option { + /// Model vocabulary size from the model config, used to bound generated + /// token IDs and logits-domain sampling controls. + pub fn model_vocab_size(&self) -> usize { self.backend.model_vocab_size() } @@ -140,17 +140,35 @@ impl TextLlm { Prompt::TokenIds(token_ids) => token_ids, }; - let mut sampling_hints = self.backend.sampling_hints()?; - sampling_hints.max_model_len = Some(self.max_model_len); + let sampling_hints = self.backend.sampling_hints()?; + let sampling_limits = SamplingLimits { + max_model_len: self.max_model_len, + max_logprobs: self.max_logprobs, + model_vocab_size: self.backend.model_vocab_size(), + tokenizer_vocab_size: self.backend.tokenizer_vocab_size(), + }; + let PreparedTextRequest { text_request, generate_request, - } = lower_text_request(request, prompt_token_ids, sampling_hints, &*tokenizer)?; + } = lower_text_request( + request, + prompt_token_ids, + sampling_hints, + sampling_limits, + &*tokenizer, + )?; let raw_stream = self.llm.generate(generate_request).await?; Ok((text_request, raw_stream)) } + /// Abort in-flight requests by their external (user-supplied) request ids. + pub async fn abort(&self, external_ids: &[String]) -> Result<()> { + self.llm.abort(external_ids).await?; + Ok(()) + } + /// Shut down the underlying LLM client and its background tasks. pub async fn shutdown(self) -> Result<()> { self.llm.shutdown().await?; diff --git a/rust/src/text/src/lower.rs b/rust/src/text/src/lower.rs index d661c99606b8..077dfcb98065 100644 --- a/rust/src/text/src/lower.rs +++ b/rust/src/text/src/lower.rs @@ -1,12 +1,17 @@ use std::collections::BTreeSet; +pub(crate) mod logprobs; +pub(crate) mod token_ids; + use vllm_engine_core_client::protocol::EngineCoreSamplingParams; use vllm_llm::GenerateRequest; use vllm_tokenizer::Tokenizer; -use crate::backend::SamplingHints; +use crate::backend::{SamplingHints, SamplingLimits}; use crate::error::{Error, Result}; use crate::request::{SamplingParams, TextRequest}; +use logprobs::validate_logprobs; +use token_ids::{validate_prompt_token_ids, validate_vocab_range}; /// One text request after it has been lowered into the raw generate boundary. #[derive(Debug)] @@ -24,9 +29,12 @@ pub fn lower_text_request( request: TextRequest, prompt_token_ids: Vec, sampling_hints: SamplingHints, + sampling_limits: SamplingLimits, tokenizer: &dyn Tokenizer, ) -> Result { let prompt_len = prompt_token_ids.len() as u32; + validate_prompt_token_ids(&prompt_token_ids, &sampling_limits)?; + let generate_request = GenerateRequest { request_id: request.request_id.clone(), prompt_token_ids, @@ -34,6 +42,7 @@ pub fn lower_text_request( sampling_params: lower_sampling_params( request.sampling_params.clone(), sampling_hints, + sampling_limits, prompt_len, tokenizer, )?, @@ -66,8 +75,8 @@ pub fn lower_sampling_params( default_min_p, default_repetition_penalty, default_max_tokens, - max_model_len, }: SamplingHints, + sampling_limits: SamplingLimits, prompt_len: u32, tokenizer: &dyn Tokenizer, ) -> Result { @@ -95,6 +104,13 @@ pub fn lower_sampling_params( vllm_xargs, } = sampling_params; + validate_logprobs( + logprobs, + prompt_logprobs, + logprob_token_ids.as_deref(), + sampling_limits, + )?; + // Mirrors the model-generation-config inheritance used by vLLM's OpenAI chat // path: https://github.com/vllm-project/vllm/blob/bc2c0c86efb28e77677a3cfb8687e976914a313a/vllm/entrypoints/openai/chat_completion/protocol.py#L424-L450 // If neither the caller nor the model provides a value, fall back to 1.0 — the @@ -105,7 +121,12 @@ pub fn lower_sampling_params( let top_k = top_k.or(default_top_k).unwrap_or(0); let min_p = min_p.or(default_min_p).unwrap_or(0.0); let repetition_penalty = repetition_penalty.or(default_repetition_penalty).unwrap_or(1.0); - let max_tokens = resolve_max_tokens(max_tokens, default_max_tokens, max_model_len, prompt_len)?; + let max_tokens = resolve_max_tokens( + max_tokens, + default_max_tokens, + sampling_limits.max_model_len, + prompt_len, + )?; let min_tokens = min_tokens.unwrap_or(0); let frequency_penalty = frequency_penalty.unwrap_or(0.0); let presence_penalty = presence_penalty.unwrap_or(0.0); @@ -121,7 +142,7 @@ pub fn lower_sampling_params( merge_unique_token_ids(&mut stop_token_ids, extra_eos_token_ids.iter().copied()); } - Ok(EngineCoreSamplingParams { + let params = EngineCoreSamplingParams { temperature, top_p, top_k, @@ -144,7 +165,9 @@ pub fn lower_sampling_params( logprob_token_ids, skip_reading_prefix_cache, extra_args: vllm_xargs, - }) + }; + validate_vocab_range(¶ms, &sampling_limits)?; + Ok(params) } /// Convert bad-word strings into token-ID sequences, following the Python vLLM @@ -189,33 +212,25 @@ fn tokenize_bad_words( /// Resolve the effective `max_tokens` for generation, mirroring vLLM Python's /// `get_max_tokens()` in `vllm/entrypoints/utils.py`. /// -/// Takes the minimum of all available limits (user-specified, generation-config -/// default, and `max_model_len - prompt_len`). When nothing is known, falls -/// back to `u32::MAX` so the engine-core can apply its own context-window -/// limit. +/// Takes the minimum of all available limits: user-specified, generation-config +/// default, and `max_model_len - prompt_len`. pub fn resolve_max_tokens( user_max_tokens: Option, default_max_tokens: Option, - max_model_len: Option, + max_model_len: u32, prompt_len: u32, ) -> Result { - let model_max_tokens = match max_model_len { - Some(max_model_len) if prompt_len >= max_model_len => { - return Err(Error::PromptTooLong { - max_model_len, - prompt_len, - }); - } - Some(max_model_len) => Some(max_model_len - prompt_len), - None => None, + let model_max_tokens = if prompt_len >= max_model_len { + return Err(Error::PromptTooLong { + max_model_len, + prompt_len, + }); + } else { + max_model_len - prompt_len }; - let fallback_max_tokens = user_max_tokens.or(default_max_tokens); - Ok([fallback_max_tokens, model_max_tokens] - .into_iter() - .flatten() - .min() - .unwrap_or(u32::MAX /* TODO: a reasonable fallback? */)) + let request_max_tokens = user_max_tokens.or(default_max_tokens); + Ok(request_max_tokens.map_or(model_max_tokens, |n| n.min(model_max_tokens))) } fn merge_unique_token_ids( @@ -233,13 +248,14 @@ fn merge_unique_token_ids( #[cfg(test)] mod tests { - use std::collections::BTreeSet; + use std::collections::{BTreeSet, HashMap}; use serial_test::file_serial; use super::*; use crate::backend::hf::HfTextBackend; use crate::backend::{SamplingHints, TextBackend as _}; + use crate::error::{LogprobsError, OutOfVocabError}; use crate::request::{Prompt, TextRequest}; /// Stub tokenizer that returns empty token IDs — sufficient for tests that @@ -272,6 +288,32 @@ mod tests { StubTokenizer } + struct FixedTokenizer { + token_ids: Vec, + } + + impl Tokenizer for FixedTokenizer { + fn encode( + &self, + _text: &str, + _add_special_tokens: bool, + ) -> vllm_tokenizer::Result> { + Ok(self.token_ids.clone()) + } + + fn decode( + &self, + _token_ids: &[u32], + _skip_special_tokens: bool, + ) -> vllm_tokenizer::Result { + Ok(String::new()) + } + + fn token_to_id(&self, _token: &str) -> Option { + None + } + } + fn sample_request() -> TextRequest { TextRequest { prompt: Prompt::TokenIds(vec![1, 2, 3]), @@ -290,16 +332,47 @@ mod tests { default_min_p: None, default_repetition_penalty: None, default_max_tokens: None, - max_model_len: None, } } + fn sample_sampling_limits() -> SamplingLimits { + SamplingLimits { + max_model_len: 1_000_000, + max_logprobs: SamplingLimits::DEFAULT_MAX_LOGPROBS, + model_vocab_size: 1000, + tokenizer_vocab_size: 2000, + } + } + + fn lower_sampling_params_with_limits( + sampling_params: SamplingParams, + sampling_limits: SamplingLimits, + ) -> Result { + lower_sampling_params( + sampling_params, + SamplingHints { + primary_eos_token_id: None, + extra_eos_token_ids: BTreeSet::new(), + default_temperature: None, + default_top_p: None, + default_top_k: None, + default_min_p: None, + default_repetition_penalty: None, + default_max_tokens: None, + }, + sampling_limits, + 3, + &stub_tokenizer(), + ) + } + #[test] fn lower_text_request_applies_python_style_eos_hints() { let prepared = lower_text_request( sample_request(), vec![1, 2, 3], sample_sampling_hints(), + sample_sampling_limits(), &stub_tokenizer(), ) .unwrap(); @@ -311,7 +384,7 @@ mod tests { top_p: 1.0, top_k: 0, seed: None, - max_tokens: 4294967295, + max_tokens: 999997, min_tokens: 0, logprobs: None, prompt_logprobs: None, @@ -350,6 +423,7 @@ mod tests { request, vec![1, 2, 3], sample_sampling_hints(), + sample_sampling_limits(), &stub_tokenizer(), ) .unwrap(); @@ -361,7 +435,7 @@ mod tests { top_p: 1.0, top_k: 0, seed: None, - max_tokens: 4294967295, + max_tokens: 999997, min_tokens: 0, logprobs: None, prompt_logprobs: None, @@ -387,6 +461,57 @@ mod tests { .assert_debug_eq(¶ms); } + #[test] + fn lower_text_request_uses_union_vocab_for_prompt_token_ids() { + lower_text_request( + sample_request(), + vec![1500], + sample_sampling_hints(), + SamplingLimits { + model_vocab_size: 2000, + tokenizer_vocab_size: 1000, + ..sample_sampling_limits() + }, + &stub_tokenizer(), + ) + .expect("model vocab extends prompt token range"); + + lower_text_request( + sample_request(), + vec![1500], + sample_sampling_hints(), + SamplingLimits { + model_vocab_size: 1000, + tokenizer_vocab_size: 2000, + ..sample_sampling_limits() + }, + &stub_tokenizer(), + ) + .expect("tokenizer vocab extends prompt token range"); + + let error = lower_text_request( + sample_request(), + vec![2000], + sample_sampling_hints(), + SamplingLimits { + model_vocab_size: 1000, + tokenizer_vocab_size: 2000, + ..sample_sampling_limits() + }, + &stub_tokenizer(), + ) + .unwrap_err(); + + assert!(matches!( + error, + Error::OutOfVocab(OutOfVocabError { + parameter: "prompt", + token_ids, + vocab_size: 2000, + }) if token_ids == vec![2000] + )); + } + #[tokio::test] #[file_serial(hf_qwen3)] async fn lower_text_request_uses_real_qwen_generation_defaults() { @@ -415,16 +540,23 @@ mod tests { default_min_p: None, default_repetition_penalty: None, default_max_tokens: None, - max_model_len: Some( - 40960, - ), } "#]] .assert_debug_eq(&hints); - let prepared = - lower_text_request(sample_request(), vec![1, 2, 3], hints, &stub_tokenizer()) - .expect("lower request"); + let prepared = lower_text_request( + sample_request(), + vec![1, 2, 3], + hints, + SamplingLimits { + max_model_len: 40960, + max_logprobs: SamplingLimits::DEFAULT_MAX_LOGPROBS, + model_vocab_size: backend.model_vocab_size(), + tokenizer_vocab_size: backend.tokenizer_vocab_size(), + }, + &stub_tokenizer(), + ) + .expect("lower request"); let params = prepared.generate_request.sampling_params; expect_test::expect![[r#" @@ -481,8 +613,8 @@ mod tests { default_min_p: None, default_repetition_penalty: None, default_max_tokens: None, - max_model_len: None, }, + sample_sampling_limits(), 3, &stub_tokenizer(), ) @@ -494,7 +626,7 @@ mod tests { top_p: 1.0, top_k: 0, seed: None, - max_tokens: 4294967295, + max_tokens: 999997, min_tokens: 0, logprobs: None, prompt_logprobs: None, @@ -550,8 +682,8 @@ mod tests { default_min_p: Some(0.1), default_repetition_penalty: Some(1.2), default_max_tokens: Some(128), - max_model_len: None, }, + sample_sampling_limits(), 3, &stub_tokenizer(), ) @@ -605,7 +737,10 @@ mod tests { default_min_p: None, default_repetition_penalty: None, default_max_tokens: None, - max_model_len: None, + }, + SamplingLimits { + max_logprobs: -1, + ..sample_sampling_limits() }, 3, &stub_tokenizer(), @@ -616,6 +751,156 @@ mod tests { assert_eq!(params.prompt_logprobs, Some(-1)); } + #[test] + fn lower_sampling_params_rejects_full_vocab_logprobs_over_default_cap() { + let error = lower_sampling_params_with_limits( + SamplingParams { + logprobs: Some(-1), + ..Default::default() + }, + sample_sampling_limits(), + ) + .unwrap_err(); + + assert!(matches!( + error, + Error::Logprobs(LogprobsError::TooManyCount { + parameter: "logprobs", + requested: 1000, + max_allowed: 20, + }) + )); + } + + #[test] + fn lower_sampling_params_expands_full_vocab_logprobs_from_model_vocab() { + let params = lower_sampling_params_with_limits( + SamplingParams { + logprobs: Some(-1), + ..Default::default() + }, + SamplingLimits { + max_logprobs: 1500, + ..sample_sampling_limits() + }, + ) + .unwrap(); + + assert_eq!(params.logprobs, Some(-1)); + } + + #[test] + fn lower_sampling_params_rejects_invalid_logprob_token_ids() { + let error = lower_sampling_params_with_limits( + SamplingParams { + logprobs: Some(1), + logprob_token_ids: Some(vec![1000]), + ..Default::default() + }, + sample_sampling_limits(), + ) + .unwrap_err(); + + assert!(matches!( + error, + Error::OutOfVocab(OutOfVocabError { + parameter: "logprob_token_ids", + token_ids, + vocab_size: 1000, + }) if token_ids == vec![1000] + )); + } + + #[test] + fn lower_sampling_params_rejects_out_of_vocab_stop_token_ids() { + let error = lower_sampling_params_with_limits( + SamplingParams { + stop_token_ids: Some(vec![999, 1000]), + ..Default::default() + }, + sample_sampling_limits(), + ) + .unwrap_err(); + + assert!(matches!( + error, + Error::OutOfVocab(OutOfVocabError { + parameter: "stop_token_ids", + token_ids, + vocab_size: 1000, + }) if token_ids == vec![1000] + )); + } + + #[test] + fn lower_sampling_params_rejects_out_of_vocab_allowed_token_ids() { + let error = lower_sampling_params_with_limits( + SamplingParams { + allowed_token_ids: Some(vec![1999, 2000]), + ..Default::default() + }, + sample_sampling_limits(), + ) + .unwrap_err(); + + assert!(matches!( + error, + Error::OutOfVocab(OutOfVocabError { + parameter: "allowed_token_ids", + token_ids, + vocab_size: 2000, + }) if token_ids == vec![2000] + )); + } + + #[test] + fn lower_sampling_params_rejects_out_of_vocab_bad_words() { + let tokenizer = FixedTokenizer { + token_ids: vec![1999, 2000], + }; + let error = lower_sampling_params( + SamplingParams { + bad_words: Some(vec!["blocked".to_string()]), + ..Default::default() + }, + SamplingHints::default(), + sample_sampling_limits(), + 3, + &tokenizer, + ) + .unwrap_err(); + + assert!(matches!( + error, + Error::OutOfVocab(OutOfVocabError { + parameter: "bad_words", + token_ids, + vocab_size: 2000, + }) if token_ids == vec![2000] + )); + } + + #[test] + fn lower_sampling_params_rejects_out_of_vocab_logit_bias() { + let error = lower_sampling_params_with_limits( + SamplingParams { + logit_bias: Some(HashMap::from([(1000, 1.0)])), + ..Default::default() + }, + sample_sampling_limits(), + ) + .unwrap_err(); + + assert!(matches!( + error, + Error::OutOfVocab(OutOfVocabError { + parameter: "logit_bias", + token_ids, + vocab_size: 1000, + }) if token_ids == vec![1000] + )); + } + #[test] fn lower_sampling_params_uses_generation_defaults_when_user_omits_values() { let params = lower_sampling_params( @@ -629,8 +914,8 @@ mod tests { default_min_p: Some(0.1), default_repetition_penalty: Some(1.2), default_max_tokens: Some(128), - max_model_len: None, }, + sample_sampling_limits(), 3, &stub_tokenizer(), ) @@ -667,7 +952,7 @@ mod tests { #[test] fn resolve_max_tokens_caps_by_model_len() { - let result = resolve_max_tokens(Some(150), None, Some(200), 100); + let result = resolve_max_tokens(Some(150), None, 200, 100); assert_eq!(result.unwrap(), 100); } @@ -680,6 +965,7 @@ mod tests { request, vec![1, 2, 3], sample_sampling_hints(), + sample_sampling_limits(), &stub_tokenizer(), ) .unwrap(); @@ -690,37 +976,31 @@ mod tests { #[test] fn resolve_max_tokens_user_smaller_than_model_limit() { - let result = resolve_max_tokens(Some(50), None, Some(200), 100); + let result = resolve_max_tokens(Some(50), None, 200, 100); assert_eq!(result.unwrap(), 50); } #[test] fn resolve_max_tokens_uses_default_when_user_omits() { - let result = resolve_max_tokens(None, Some(64), Some(200), 100); + let result = resolve_max_tokens(None, Some(64), 200, 100); assert_eq!(result.unwrap(), 64); } #[test] fn resolve_max_tokens_default_capped_by_model_len() { - let result = resolve_max_tokens(None, Some(256), Some(200), 100); + let result = resolve_max_tokens(None, Some(256), 200, 100); assert_eq!(result.unwrap(), 100); } #[test] - fn resolve_max_tokens_no_model_len_falls_back() { - let result = resolve_max_tokens(Some(9999), None, None, 100); - assert_eq!(result.unwrap(), 9999); - } - - #[test] - fn resolve_max_tokens_no_limits_known_falls_back_to_u32_max() { - let result = resolve_max_tokens(None, None, None, 100); - assert_eq!(result.unwrap(), u32::MAX); + fn resolve_max_tokens_uses_model_limit_when_user_omits() { + let result = resolve_max_tokens(None, None, 200, 100); + assert_eq!(result.unwrap(), 100); } #[test] fn resolve_max_tokens_prompt_too_long() { - let result = resolve_max_tokens(Some(10), None, Some(100), 100); + let result = resolve_max_tokens(Some(10), None, 100, 100); assert!(matches!( result, Err(Error::PromptTooLong { @@ -732,7 +1012,7 @@ mod tests { #[test] fn resolve_max_tokens_prompt_exceeds_model_len() { - let result = resolve_max_tokens(Some(10), None, Some(100), 200); + let result = resolve_max_tokens(Some(10), None, 100, 200); assert!(matches!( result, Err(Error::PromptTooLong { diff --git a/rust/src/text/src/lower/logprobs.rs b/rust/src/text/src/lower/logprobs.rs new file mode 100644 index 000000000000..3c90f3391071 --- /dev/null +++ b/rust/src/text/src/lower/logprobs.rs @@ -0,0 +1,112 @@ +//! Python-compatible validation for logprobs sampling params. +//! +//! `-1` is expanded only for bounds checks. The original request values are +//! passed through to engine-core. + +use crate::backend::SamplingLimits; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum LogprobsError { + #[error("{parameter} must be non-negative or -1, got {value}")] + InvalidCount { parameter: &'static str, value: i32 }, + #[error( + "requested {parameter} of {requested}, which is greater than max allowed: {max_allowed}" + )] + TooManyCount { + parameter: &'static str, + requested: usize, + max_allowed: usize, + }, + #[error( + "requested logprob_token_ids of length {requested}, \ + which is greater than max allowed: {max_allowed}" + )] + TooManyTokenIds { + requested: usize, + max_allowed: usize, + }, + #[error( + "when both logprobs and logprob_token_ids are set, logprobs must equal \ + len(logprob_token_ids). Got logprobs={logprobs}, len(logprob_token_ids)={num_token_ids}." + )] + TokenIdsMismatch { logprobs: i32, num_token_ids: usize }, +} + +/// Validate logprobs count sampling parameters. +pub(super) fn validate_logprobs( + logprobs: Option, + prompt_logprobs: Option, + logprob_token_ids: Option<&[u32]>, + sampling_limits: SamplingLimits, +) -> Result<(), LogprobsError> { + let vocab_size = sampling_limits.model_vocab_size; + let max_logprobs = + normalize_logprobs_count(sampling_limits.max_logprobs, vocab_size, "max_logprobs")?; + + validate_logprobs_count(logprobs, max_logprobs, vocab_size, "logprobs")?; + validate_logprobs_count(prompt_logprobs, max_logprobs, vocab_size, "prompt_logprobs")?; + validate_logprob_token_ids(logprobs, logprob_token_ids) +} + +fn validate_logprobs_count( + requested: Option, + max_logprobs: usize, + vocab_size: usize, + parameter: &'static str, +) -> Result<(), LogprobsError> { + let Some(requested) = requested else { + return Ok(()); + }; + + let requested = normalize_logprobs_count(requested, vocab_size, parameter)?; + if requested > max_logprobs { + return Err(LogprobsError::TooManyCount { + parameter, + requested, + max_allowed: max_logprobs, + }); + } + + Ok(()) +} + +pub(super) fn validate_logprob_token_ids( + logprobs: Option, + logprob_token_ids: Option<&[u32]>, +) -> Result<(), LogprobsError> { + let Some(logprob_token_ids) = logprob_token_ids else { + return Ok(()); + }; + + let n = logprob_token_ids.len(); + if n > SamplingLimits::MAX_LOGPROB_TOKEN_IDS { + return Err(LogprobsError::TooManyTokenIds { + requested: n, + max_allowed: SamplingLimits::MAX_LOGPROB_TOKEN_IDS, + }); + } + + if let Some(logprobs) = logprobs + && logprobs != n as i32 + { + return Err(LogprobsError::TokenIdsMismatch { + logprobs, + num_token_ids: n, + }); + } + + Ok(()) +} + +fn normalize_logprobs_count( + value: i32, + vocab_size: usize, + parameter: &'static str, +) -> Result { + match value { + -1 => Ok(vocab_size), + value if value < 0 => Err(LogprobsError::InvalidCount { parameter, value }), + value => Ok(value as usize), + } +} diff --git a/rust/src/text/src/lower/token_ids.rs b/rust/src/text/src/lower/token_ids.rs new file mode 100644 index 000000000000..e434af92f11c --- /dev/null +++ b/rust/src/text/src/lower/token_ids.rs @@ -0,0 +1,111 @@ +use std::result::Result; + +use thiserror::Error; +use vllm_engine_core_client::protocol::EngineCoreSamplingParams; + +use crate::SamplingLimits; + +#[derive(Debug, Error)] +#[error( + "token_id(s) {token_ids:?} in {parameter} contain out-of-vocab token ids. \ + Vocabulary size: {vocab_size}" +)] +pub struct OutOfVocabError { + pub parameter: &'static str, + pub token_ids: Vec, + pub vocab_size: usize, +} + +fn validate_param( + parameter: &'static str, + token_ids: impl IntoIterator, + vocab_size: usize, +) -> Result<(), OutOfVocabError> { + let invalid_token_ids: Vec<_> = token_ids + .into_iter() + .filter(|&token_id| token_id as usize >= vocab_size) + .collect(); + if invalid_token_ids.is_empty() { + return Ok(()); + } + + Err(OutOfVocabError { + parameter, + token_ids: invalid_token_ids, + vocab_size, + }) +} + +/// Validate that pre-tokenized prompt IDs are within the engine-visible prompt +/// vocabulary range. +pub(crate) fn validate_prompt_token_ids( + prompt_token_ids: &[u32], + limits: &SamplingLimits, +) -> Result<(), OutOfVocabError> { + validate_param( + "prompt", + prompt_token_ids.iter().copied(), + limits.prompt_token_vocab_size(), + ) +} + +/// Validate that token IDs in text sampling parameters are within their +/// parameter-specific vocabulary ranges. +pub(crate) fn validate_vocab_range( + params: &EngineCoreSamplingParams, + limits: &SamplingLimits, +) -> Result<(), OutOfVocabError> { + validate_param( + "stop_token_ids", + params.stop_token_ids.iter().copied(), + limits.model_vocab_size, + )?; + + if let Some(token_ids) = params.allowed_token_ids.as_deref() { + validate_param( + "allowed_token_ids", + token_ids.iter().copied(), + limits.tokenizer_vocab_size, + )?; + } + + if let Some(logit_bias) = params.logit_bias.as_ref() { + validate_param( + "logit_bias", + logit_bias.keys().copied(), + limits.model_vocab_size, + )?; + } + + if let Some(token_ids) = params.logprob_token_ids.as_deref() { + validate_param( + "logprob_token_ids", + token_ids.iter().copied(), + limits.model_vocab_size, + )?; + } + + if let Some(bad_words_token_ids) = params.bad_words_token_ids.as_deref() { + validate_param( + "bad_words", + bad_words_token_ids.iter().flatten().copied(), + limits.tokenizer_vocab_size, + )?; + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validate_vocab_range_rejects_out_of_vocab_ids() { + let error = validate_param("logprob_token_ids", [5_u32, 1000, 1001], 1000).unwrap_err(); + + assert_eq!(error.parameter, "logprob_token_ids"); + assert_eq!(error.token_ids, vec![1000, 1001]); + assert_eq!(error.vocab_size, 1000); + } +} diff --git a/rust/src/tool-parser/benches/qwen3_coder.rs b/rust/src/tool-parser/benches/qwen3_coder.rs index 850badaac527..b4f26ac5cdb8 100644 --- a/rust/src/tool-parser/benches/qwen3_coder.rs +++ b/rust/src/tool-parser/benches/qwen3_coder.rs @@ -10,6 +10,7 @@ use utils::{feed_external_parser, feed_parser, openai_tools}; const CHUNK_CHARS: usize = 7; const LONG_NORMAL_TEXT_REPEATS: usize = 2048; +const LONG_TOOL_BODY_REPEATS: usize = 8192; fn mixed_fixture() -> String { concat!( @@ -39,6 +40,17 @@ fn long_normal_text_fixture() -> String { line.repeat(LONG_NORMAL_TEXT_REPEATS) } +fn long_tool_call_fixture() -> String { + let location = "x".repeat(LONG_TOOL_BODY_REPEATS); + format!( + "\n\ + \n\ + {location}\n\ + \n\ + " + ) +} + fn native_parser(tools: &[Tool]) -> Box { Qwen3CoderToolParser::create(tools).expect("Qwen Coder parser should initialize") } @@ -112,6 +124,7 @@ fn bench_qwen3_coder(c: &mut Criterion) { let tools = test_tools(); let mixed_text = mixed_fixture(); let long_normal_text = long_normal_text_fixture(); + let long_tool_call = long_tool_call_fixture(); run_stream_group( c, @@ -132,6 +145,16 @@ fn bench_qwen3_coder(c: &mut Criterion) { &long_normal_text, 0, ); + + run_stream_group( + c, + "qwen3_coder/long_tool_call_body", + &tools, + &long_tool_call, + CHUNK_CHARS, + "", + 1, + ); } criterion_group!(benches, bench_qwen3_coder); diff --git a/rust/src/tool-parser/python/src/lib.rs b/rust/src/tool-parser/python/src/lib.rs index 81aed04b1cc4..e5ae0fa7b69a 100644 --- a/rust/src/tool-parser/python/src/lib.rs +++ b/rust/src/tool-parser/python/src/lib.rs @@ -38,6 +38,8 @@ macro_rules! tool_parser_factory { // Export a tool parser to Python by registering it here. tool_parser_factory! { + MinimaxM3ToolParser, + // Below are the parsers just for testing purposes on Python side. DeepSeekV4ToolParser, KimiK2ToolParser, diff --git a/rust/src/tool-parser/src/deepseek_dsml/mod.rs b/rust/src/tool-parser/src/deepseek_dsml/mod.rs index b44135186545..1a2031dd3d7f 100644 --- a/rust/src/tool-parser/src/deepseek_dsml/mod.rs +++ b/rust/src/tool-parser/src/deepseek_dsml/mod.rs @@ -5,7 +5,7 @@ use winnow::stream::Partial; use winnow::token::{literal, rest, take_until}; use super::parameters::ToolSchemas; -use super::utils::{parse_buffered_event, safe_text_len}; +use super::utils::{MarkerScanState, parse_buffered_event, safe_text_len, take_until_marker}; use super::{Result, ToolCallDelta, ToolParserOutput}; use crate::Tool; @@ -39,10 +39,10 @@ impl DsmlTokens { }; } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] enum DsmlMode { Text, - ToolBlock, + ToolBlock { invoke_end_scan: MarkerScanState }, Done, } @@ -94,7 +94,11 @@ impl DeepSeekDsmlToolParser { DsmlEvent::Text { len: consumed_len } => { output.normal_text.push_str(&self.buffer[..consumed_len]); } - DsmlEvent::ToolCallsStart => self.mode = DsmlMode::ToolBlock, + DsmlEvent::ToolCallsStart => { + self.mode = DsmlMode::ToolBlock { + invoke_end_scan: MarkerScanState::default(), + }; + } DsmlEvent::Invoke { name, raw_params } => { let mut arguments = serde_json::Map::with_capacity(raw_params.len()); for param in raw_params { @@ -140,7 +144,7 @@ impl DeepSeekDsmlToolParser { self.buffer.push_str(chunk); while let Some((event, consumed_len)) = parse_buffered_event(&self.buffer, |input| { - parse_next_dsml_event(input, self.mode, self.tokens) + parse_next_dsml_event(input, &mut self.mode, self.tokens) })? { self.apply_event(event, output)?; self.buffer.drain(..consumed_len); @@ -154,7 +158,7 @@ impl DeepSeekDsmlToolParser { match self.mode { DsmlMode::Text => output.normal_text.push_str(&self.buffer), DsmlMode::Done => {} - DsmlMode::ToolBlock => { + DsmlMode::ToolBlock { .. } => { return Err(parsing_failed!("incomplete DeepSeek DSML tool call")); } } @@ -166,12 +170,14 @@ impl DeepSeekDsmlToolParser { /// Parse a DSML event for the current parser mode. fn parse_next_dsml_event( input: &mut DsmlInput<'_>, - mode: DsmlMode, + mode: &mut DsmlMode, tokens: DsmlTokens, ) -> ModalResult { match mode { DsmlMode::Text => parse_text_event(input, tokens), - DsmlMode::ToolBlock => parse_tool_block_event(input, tokens), + DsmlMode::ToolBlock { invoke_end_scan } => { + parse_tool_block_event(input, tokens, invoke_end_scan) + } DsmlMode::Done => ignored_rest_event(input), } } @@ -186,11 +192,16 @@ fn parse_text_event(input: &mut DsmlInput<'_>, tokens: DsmlTokens) -> ModalResul } /// Parse a tool-block DSML event. -fn parse_tool_block_event(input: &mut DsmlInput<'_>, tokens: DsmlTokens) -> ModalResult { +fn parse_tool_block_event( + input: &mut DsmlInput<'_>, + tokens: DsmlTokens, + invoke_end_scan: &mut MarkerScanState, +) -> ModalResult { ws0.void().parse_next(input)?; - alt((invoke_event, |input: &mut DsmlInput<'_>| { - tool_calls_end_event(input, tokens) - })) + alt(( + |input: &mut DsmlInput<'_>| invoke_event(input, invoke_end_scan), + |input: &mut DsmlInput<'_>| tool_calls_end_event(input, tokens), + )) .parse_next(input) } @@ -217,14 +228,17 @@ fn safe_text_event(input: &mut DsmlInput<'_>, tokens: DsmlTokens) -> ModalResult } /// Parse a DSML invoke block. -fn invoke_event(input: &mut DsmlInput<'_>) -> ModalResult { +fn invoke_event( + input: &mut DsmlInput<'_>, + invoke_end_scan: &mut MarkerScanState, +) -> ModalResult { let (name, body) = seq!( _: literal(INVOKE_START), _: ws1, dsml_name_attr, _: ws0, _: ">", - take_until(0.., INVOKE_END), + take_until_marker(INVOKE_END, invoke_end_scan), _: literal(INVOKE_END), ) .parse_next(input)?; diff --git a/rust/src/tool-parser/src/glm_xml/mod.rs b/rust/src/tool-parser/src/glm_xml/mod.rs index 9a5a39dabbcf..ceeb9a751739 100644 --- a/rust/src/tool-parser/src/glm_xml/mod.rs +++ b/rust/src/tool-parser/src/glm_xml/mod.rs @@ -5,7 +5,7 @@ use winnow::stream::Partial; use winnow::token::{literal, rest, take_until, take_while}; use super::parameters::ToolSchemas; -use super::utils::{parse_buffered_event, safe_text_len}; +use super::utils::{MarkerScanState, parse_buffered_event, safe_text_len, take_until_marker}; use super::{Result, ToolCallDelta, ToolParserOutput}; use crate::Tool; @@ -24,10 +24,10 @@ const ARG_VALUE_END: &str = ""; type GlmInput<'i> = Partial<&'i str>; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] enum GlmMode { Text, - ToolCall, + ToolCall { tool_call_end_scan: MarkerScanState }, AfterToolCall, } @@ -81,7 +81,11 @@ impl GlmXmlToolParser { GlmEvent::Text { len: consumed_len } => { output.normal_text.push_str(&self.buffer[..consumed_len]); } - GlmEvent::ToolCallStart => self.mode = GlmMode::ToolCall, + GlmEvent::ToolCallStart => { + self.mode = GlmMode::ToolCall { + tool_call_end_scan: MarkerScanState::default(), + }; + } GlmEvent::ToolCall { name, raw_params } => { self.mode = GlmMode::AfterToolCall; let arguments = self.tool_parameters.convert_params_with_schema(&name, raw_params); @@ -110,7 +114,7 @@ impl GlmXmlToolParser { self.buffer.push_str(chunk); while let Some((event, consumed_len)) = parse_buffered_event(&self.buffer, |input| { - parse_next_glm_event(input, self.mode, self.separator) + parse_next_glm_event(input, &mut self.mode, self.separator) })? { self.apply_event(event, output)?; self.buffer.drain(..consumed_len); @@ -124,7 +128,9 @@ impl GlmXmlToolParser { if !self.buffer.is_empty() { match self.mode { GlmMode::Text => output.normal_text.push_str(&self.buffer), - GlmMode::ToolCall => return Err(parsing_failed!("incomplete GLM MoE tool call")), + GlmMode::ToolCall { .. } => { + return Err(parsing_failed!("incomplete GLM MoE tool call")); + } GlmMode::AfterToolCall => {} } } @@ -136,12 +142,14 @@ impl GlmXmlToolParser { /// Parse a GLM event for the current parser mode. fn parse_next_glm_event( input: &mut GlmInput<'_>, - mode: GlmMode, + mode: &mut GlmMode, separator: Separator, ) -> ModalResult { match mode { GlmMode::Text => parse_text_event(input), - GlmMode::ToolCall => tool_call_event(input, separator), + GlmMode::ToolCall { tool_call_end_scan } => { + tool_call_event(input, separator, tool_call_end_scan) + } GlmMode::AfterToolCall => after_tool_call_event(input), } } @@ -173,9 +181,13 @@ fn ignored_rest_event(input: &mut GlmInput<'_>) -> ModalResult { } /// Parse a complete GLM tool call. -fn tool_call_event(input: &mut GlmInput<'_>, separator: Separator) -> ModalResult { +fn tool_call_event( + input: &mut GlmInput<'_>, + separator: Separator, + tool_call_end_scan: &mut MarkerScanState, +) -> ModalResult { let (body,) = seq!( - take_until(0.., TOOL_CALL_END), + take_until_marker(TOOL_CALL_END, tool_call_end_scan), _: literal(TOOL_CALL_END), ) .parse_next(input)?; diff --git a/rust/src/tool-parser/src/hy_v3.rs b/rust/src/tool-parser/src/hy_v3.rs index 32f0e4d9e75e..7c850d51aa12 100644 --- a/rust/src/tool-parser/src/hy_v3.rs +++ b/rust/src/tool-parser/src/hy_v3.rs @@ -5,7 +5,7 @@ use winnow::stream::Partial; use winnow::token::{literal, rest, take_until}; use super::parameters::ToolSchemas; -use super::utils::{parse_buffered_event, safe_text_len}; +use super::utils::{MarkerScanState, parse_buffered_event, safe_text_len, take_until_marker}; use super::{Result, ToolCallDelta, ToolParser, ToolParserOutput}; use crate::Tool; @@ -21,10 +21,10 @@ const ARG_VALUE_END: &str = ""; type HyV3Input<'i> = Partial<&'i str>; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] enum HyV3Mode { Text, - ToolBlock, + ToolBlock { tool_call_end_scan: MarkerScanState }, Done, } @@ -81,7 +81,11 @@ impl HyV3ToolParser { HyV3Event::Text { len: consumed_len } => { output.normal_text.push_str(&self.buffer[..consumed_len]); } - HyV3Event::ToolBlockStart => self.mode = HyV3Mode::ToolBlock, + HyV3Event::ToolBlockStart => { + self.mode = HyV3Mode::ToolBlock { + tool_call_end_scan: MarkerScanState::default(), + }; + } HyV3Event::ToolCall { name, raw_params } => { let arguments = self.tool_parameters.convert_params_with_schema(&name, raw_params); let arguments = serde_json::to_string(&arguments) @@ -113,7 +117,7 @@ impl ToolParser for HyV3ToolParser { self.buffer.push_str(chunk); while let Some((event, consumed_len)) = parse_buffered_event(&self.buffer, |input| { - parse_next_hy_v3_event(input, self.mode) + parse_next_hy_v3_event(input, &mut self.mode) })? { self.apply_event(event, output)?; self.buffer.drain(..consumed_len); @@ -126,7 +130,7 @@ impl ToolParser for HyV3ToolParser { let mut output = ToolParserOutput::default(); match self.mode { HyV3Mode::Text => output.normal_text.push_str(&self.buffer), - HyV3Mode::ToolBlock => return Err(parsing_failed!("incomplete HY3 tool call")), + HyV3Mode::ToolBlock { .. } => return Err(parsing_failed!("incomplete HY3 tool call")), HyV3Mode::Done => {} } let _ = self.reset(); @@ -141,10 +145,15 @@ impl ToolParser for HyV3ToolParser { } /// Parse a HY3 event for the current parser mode. -fn parse_next_hy_v3_event(input: &mut HyV3Input<'_>, mode: HyV3Mode) -> ModalResult { +fn parse_next_hy_v3_event( + input: &mut HyV3Input<'_>, + mode: &mut HyV3Mode, +) -> ModalResult { match mode { HyV3Mode::Text => parse_text_event(input), - HyV3Mode::ToolBlock => parse_tool_block_event(input), + HyV3Mode::ToolBlock { tool_call_end_scan } => { + parse_tool_block_event(input, tool_call_end_scan) + } HyV3Mode::Done => ignored_rest_event(input), } } @@ -165,8 +174,14 @@ fn safe_text_event(input: &mut HyV3Input<'_>) -> ModalResult { } /// Parse one event inside a HY3 tool block. -fn parse_tool_block_event(input: &mut HyV3Input<'_>) -> ModalResult { - alt((tool_block_end_event, tool_call_event)).parse_next(input) +fn parse_tool_block_event( + input: &mut HyV3Input<'_>, + tool_call_end_scan: &mut MarkerScanState, +) -> ModalResult { + alt((tool_block_end_event, |input: &mut HyV3Input<'_>| { + tool_call_event(input, tool_call_end_scan) + })) + .parse_next(input) } /// Parse a HY3 tool-block end marker. @@ -175,13 +190,16 @@ fn tool_block_end_event(input: &mut HyV3Input<'_>) -> ModalResult { } /// Parse a complete HY3 tool-call block. -fn tool_call_event(input: &mut HyV3Input<'_>) -> ModalResult { +fn tool_call_event( + input: &mut HyV3Input<'_>, + tool_call_end_scan: &mut MarkerScanState, +) -> ModalResult { let (name, body) = seq!( _: ws0, _: literal(TOOL_CALL_START), take_until(0.., TOOL_SEP), _: literal(TOOL_SEP), - take_until(0.., TOOL_CALL_END), + take_until_marker(TOOL_CALL_END, tool_call_end_scan), _: literal(TOOL_CALL_END), ) .parse_next(input)?; diff --git a/rust/src/tool-parser/src/json/granite4.rs b/rust/src/tool-parser/src/json/granite4.rs new file mode 100644 index 000000000000..a70c0645400b --- /dev/null +++ b/rust/src/tool-parser/src/json/granite4.rs @@ -0,0 +1,495 @@ +use winnow::ascii::multispace0 as ws0; +use winnow::combinator::{alt, peek, seq}; +use winnow::error::{ContextError, ErrMode, ModalResult, StrContext}; +use winnow::prelude::*; +use winnow::token::{any, literal}; + +use super::{ + JsonToolCallConfig, JsonToolCallEvent, JsonToolCallWhitespace, JsonToolInput, + tool_call_header_event, +}; +use crate::utils::{ + JsonObjectScanState, json_str, parse_buffered_event, safe_text_len, take_json_object, +}; +use crate::{Result, Tool, ToolCallDelta, ToolParser, ToolParserOutput}; + +const TOOL_CALL_START: &str = ""; +const TOOL_CALL_END: &str = ""; + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Granite4Mode { + Text, + Header, + /// Parsing the arguments value: + /// `None` until the first byte decides object vs string; + /// `Some` while streaming an object value. + Args { + json_scan: Option, + }, + /// Arguments done; consume the object's closing `}` and ``. + Close, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Granite4Event { + Text { + len: usize, + }, + ToolCallStart, + ToolCallHeader { + function_name: String, + }, + /// Verbatim bytes of an object-valued arguments payload; `complete` once the + /// object scan reaches its closing brace. + ObjectArgsDelta { + len: usize, + complete: bool, + }, + /// Decoded contents of a string-valued arguments payload. + StringArgs { + decoded: String, + }, + ToolCallEnd, +} + +/// Tool parser for Granite 4 `` JSON tool calls. +/// +/// Example tool call content: +/// +/// ```text +/// {"name": "get_weather", "arguments": {"city": "Boston"}} +/// ``` +/// +/// Parallel calls are repeated `` blocks with ordinary +/// content interleaved between them. This reuses the shared JSON helpers for +/// everything except one Granite 4 specific step (`args_event`): the `arguments` +/// value may be a JSON object (kept verbatim) **or** a JSON string whose decoded +/// contents are the arguments (the `# test granite behavior` case in Python). +pub struct Granite4ToolParser { + buffer: String, + mode: Granite4Mode, + active_tool_index: Option, + emitted_tool_count: usize, +} + +impl Granite4ToolParser { + /// Create a Granite 4 tool parser. + fn new(_tools: &[Tool]) -> Self { + Self { + buffer: String::new(), + mode: Granite4Mode::Text, + active_tool_index: None, + emitted_tool_count: 0, + } + } + + /// Apply one parsed Granite 4 event to parser state and output. + fn apply_event(&mut self, event: Granite4Event, output: &mut ToolParserOutput) -> Result<()> { + match event { + Granite4Event::Text { len } => output.normal_text.push_str(&self.buffer[..len]), + Granite4Event::ToolCallStart => self.mode = Granite4Mode::Header, + Granite4Event::ToolCallHeader { function_name } => { + let tool_index = self.emitted_tool_count; + self.emitted_tool_count += 1; + self.active_tool_index = Some(tool_index); + self.mode = Granite4Mode::Args { json_scan: None }; + output.calls.push(ToolCallDelta { + tool_index, + name: Some(function_name), + arguments: String::new(), + }); + } + Granite4Event::ObjectArgsDelta { len, complete } => { + let arguments = self.buffer[..len].to_string(); + self.push_arguments(arguments, output)?; + if complete { + self.mode = Granite4Mode::Close; + } + } + Granite4Event::StringArgs { decoded } => { + self.push_arguments(decoded, output)?; + self.mode = Granite4Mode::Close; + } + Granite4Event::ToolCallEnd => { + self.active_tool_index = None; + self.mode = Granite4Mode::Text; + } + } + Ok(()) + } + + /// Append one arguments delta to the active tool call. + fn push_arguments(&self, arguments: String, output: &mut ToolParserOutput) -> Result<()> { + let Some(tool_index) = self.active_tool_index else { + return Err(parsing_failed!( + "Granite4 arguments without an active tool call" + )); + }; + output.calls.push(ToolCallDelta { + tool_index, + name: None, + arguments, + }); + Ok(()) + } + + fn reset(&mut self) -> String { + self.mode = Granite4Mode::Text; + self.active_tool_index = None; + self.emitted_tool_count = 0; + std::mem::take(&mut self.buffer) + } +} + +impl ToolParser for Granite4ToolParser { + fn create(tools: &[Tool]) -> Result> + where + Self: Sized + 'static, + { + Ok(Box::new(Self::new(tools))) + } + + fn parse_into(&mut self, chunk: &str, output: &mut ToolParserOutput) -> Result<()> { + self.buffer.push_str(chunk); + + while let Some((event, consumed_len)) = parse_buffered_event(&self.buffer, |input| { + parse_next_granite4_event(input, &mut self.mode) + })? { + self.apply_event(event, output)?; + self.buffer.drain(..consumed_len); + } + + Ok(()) + } + + fn finish(&mut self) -> Result { + let mut output = ToolParserOutput::default(); + match &self.mode { + Granite4Mode::Text => output.normal_text.push_str(&self.buffer), + Granite4Mode::Header | Granite4Mode::Args { .. } | Granite4Mode::Close => { + return Err(parsing_failed!("incomplete Granite4 tool call")); + } + } + let _ = self.reset(); + Ok(output) + } + + fn reset(&mut self) -> String { + Granite4ToolParser::reset(self) + } +} + +/// Parse a Granite 4 event for the current parser mode. +fn parse_next_granite4_event( + input: &mut JsonToolInput<'_>, + mode: &mut Granite4Mode, +) -> ModalResult { + match mode { + Granite4Mode::Text => text_event(input), + Granite4Mode::Header => header_event(input), + Granite4Mode::Args { json_scan } => args_event(input, json_scan), + Granite4Mode::Close => close_event(input), + } +} + +/// Parse content text or the start of a `` block. *(reuses `safe_text_len`)* +fn text_event(input: &mut JsonToolInput<'_>) -> ModalResult { + alt(( + |input: &mut JsonToolInput<'_>| { + seq!(_: literal(TOOL_CALL_START), _: ws0) + .value(Granite4Event::ToolCallStart) + .parse_next(input) + }, + |input: &mut JsonToolInput<'_>| { + safe_text_len(input, TOOL_CALL_START).map(|len| Granite4Event::Text { len }) + }, + )) + .parse_next(input) +} + +/// Parse the `{"name":"X","arguments":` header before the value. *(reuses `tool_call_header_event`)* +fn header_event(input: &mut JsonToolInput<'_>) -> ModalResult { + const CONFIG: JsonToolCallConfig = JsonToolCallConfig { + parser_name: "Granite4", + start_marker: "", + end_marker: "", + marker_whitespace: JsonToolCallWhitespace::Optional, + delimiter: None, + name_key: "name", + arguments_key: &["arguments"], + }; + + match tool_call_header_event(input, CONFIG)? { + JsonToolCallEvent::ToolCallHeader { function_name } => { + Ok(Granite4Event::ToolCallHeader { function_name }) + } + _ => unreachable!("tool_call_header_event only emits ToolCallHeader"), + } +} + +/// Parse one arguments-value event. +/// +/// GRANITE 4 SPECIFIC - the sole behavior that differs from the shared +/// `` JSON parsers. The value is either a JSON object (kept verbatim, +/// streamed incrementally via `take_json_object`) or an escaped JSON string +/// (decoded whole via `json_str`). The string form is why we cannot just forward +/// raw arg bytes like the sibling parsers do: an escaped string only resolves +/// once seen whole and unescaped. +fn args_event( + input: &mut JsonToolInput<'_>, + json_scan: &mut Option, +) -> ModalResult { + if let Some(scan) = json_scan { + let len = take_json_object(input, scan)?; + return Ok(Granite4Event::ObjectArgsDelta { + len, + complete: scan.complete(), + }); + } + + match peek(any).parse_next(input)? { + '{' => { + let mut scan = JsonObjectScanState::default(); + let len = take_json_object(input, &mut scan)?; + let complete = scan.complete(); + *json_scan = Some(scan); + Ok(Granite4Event::ObjectArgsDelta { len, complete }) + } + '"' => Ok(Granite4Event::StringArgs { + decoded: json_str(input)?, + }), + _ => { + let mut error = ContextError::new(); + error.push(StrContext::Label("Granite4 arguments")); + Err(ErrMode::Cut(error)) + } + } +} + +/// Parse the tool-call object's closing `}` and the `` end marker. +fn close_event(input: &mut JsonToolInput<'_>) -> ModalResult { + seq!(_: ws0, _: literal("}"), _: ws0, _: literal(TOOL_CALL_END)) + .value(Granite4Event::ToolCallEnd) + .parse_next(input) +} + +#[cfg(test)] +mod tests { + use expect_test::expect; + use thiserror_ext::AsReport; + + use super::Granite4ToolParser; + use crate::test_utils::{collect_stream, split_by_chars, test_tools}; + use crate::{ToolParser, ToolParserOutput, ToolParserTestExt as _}; + + #[test] + fn granite4_parse_complete_without_tool_call_keeps_text() { + let mut parser = Granite4ToolParser::new(&test_tools()); + let output = parser.parse_complete("Hello, world!").unwrap(); + + assert_eq!(output.normal_text, "Hello, world!"); + assert!(output.calls.is_empty()); + } + + #[test] + fn granite4_parse_complete_object_args() { + let mut parser = Granite4ToolParser::new(&test_tools()); + let output = parser + .parse_complete( + r#"{"name":"get_weather","arguments":{"city":"Boston"}}"#, + ) + .unwrap(); + + assert_eq!(output.normal_text, ""); + assert_eq!(output.calls.len(), 1); + assert_eq!(output.calls[0].name.as_deref(), Some("get_weather")); + assert_eq!(output.calls[0].arguments, r#"{"city":"Boston"}"#); + } + + #[test] + fn granite4_parse_complete_string_args() { + // GRANITE4-SPECIFIC: `arguments` may be a pre-serialized JSON string; its + // decoded contents become the arguments. + let mut parser = Granite4ToolParser::new(&test_tools()); + let output = parser + .parse_complete( + r#"{"name":"get_weather","arguments":"{\"city\":\"Boston\"}"}"#, + ) + .unwrap(); + + assert_eq!(output.calls.len(), 1); + assert_eq!(output.calls[0].name.as_deref(), Some("get_weather")); + assert_eq!(output.calls[0].arguments, r#"{"city":"Boston"}"#); + } + + #[test] + fn granite4_extracts_interleaved_content_and_mixed_args() { + let mut parser = Granite4ToolParser::new(&test_tools()); + let output = parser + .parse_complete( + r#"before {"name":"find_bbox","arguments":"{\"x\":1}"} middle {"name":"get_weather","arguments":{"city":"Boston"}} after"#, + ) + .unwrap(); + + expect![[r#" + ToolParserOutput { + normal_text: "before middle after", + calls: [ + ToolCallDelta { + tool_index: 0, + name: Some( + "find_bbox", + ), + arguments: "{\"x\":1}", + }, + ToolCallDelta { + tool_index: 1, + name: Some( + "get_weather", + ), + arguments: "{\"city\":\"Boston\"}", + }, + ], + } + "#]] + .assert_debug_eq(&output); + } + + #[test] + fn granite4_streaming_handles_split_markers() { + let input = r#"hello {"name":"get_weather","arguments":{"city":"Tokyo"}} bye"#; + let chunks = split_by_chars(input, 5); + let mut parser = Granite4ToolParser::new(&test_tools()); + + let output = collect_stream(&mut parser, &chunks); + + assert_eq!(output.normal_text, "hello bye"); + assert_eq!(output.calls.len(), 1); + assert_eq!(output.calls[0].name.as_deref(), Some("get_weather")); + assert_eq!(output.calls[0].arguments, r#"{"city":"Tokyo"}"#); + } + + #[test] + fn granite4_streaming_emits_object_argument_deltas() { + let mut parser = Granite4ToolParser::new(&test_tools()); + let chunks = [ + r#"{"name":"get_weather","arguments":"#, + r#"{"city":"#, + r#""Beijing""#, + r#"}"#, + r#"}"#, + ]; + + let mut output = ToolParserOutput::default(); + let mut observed_arguments = Vec::new(); + for chunk in chunks { + let next = parser.parse_chunk(chunk).unwrap(); + observed_arguments.extend( + next.calls + .iter() + .filter(|call| call.name.is_none()) + .map(|call| call.arguments.clone()), + ); + output.append(next); + } + output.append(parser.finish().unwrap()); + + assert_eq!(observed_arguments, [r#"{"city":"#, r#""Beijing""#, r#"}"#]); + assert_eq!( + output.coalesce_calls().calls[0].arguments, + r#"{"city":"Beijing"}"# + ); + } + + #[test] + fn granite4_string_args_split_across_chunks() { + let input = r#"{"name":"f","arguments":"{\"a\":1}"}"#; + let chunks = split_by_chars(input, 3); + let mut parser = Granite4ToolParser::new(&test_tools()); + + let output = collect_stream(&mut parser, &chunks); + + assert_eq!(output.calls.len(), 1); + assert_eq!(output.calls[0].name.as_deref(), Some("f")); + assert_eq!(output.calls[0].arguments, r#"{"a":1}"#); + } + + #[test] + fn granite4_streaming_handles_marker_and_json_whitespace() { + // Granite spaces the markers (` {…} `) and the JSON + // (`"name": …`). Since `args_event` has no leading `ws0`, this guards that + // the header consumes the whitespace before the arguments value. + let input = concat!( + "Here goes the bbox call: \n", + r#" {"name": "find_bbox", "arguments": "{\"coordinates\": [[23.54, 43.1], [-12.2, 54.3], [4, 5]], \"coordinate_type\": \"latlong\"}"} "#, + " Now the stock price call: \n ", + r#" {"name": "get_stock_price", "arguments": {"symbol": "AAPL", "start_date": "2021-01-01", "end_date": "2021-12-31"}} "#, + " Now another bbox call: \n ", + r#" {"name": "find_bbox", "arguments": "{\"coordinates\": [[23.54, 43.1], [-12.2, 54.3], [4, 5]], \"coordinate_type\": \"latlong\"}"} "#, + " See? I'm a helpful assistant.", + ); + let chunks = split_by_chars(input, 3); + let mut parser = Granite4ToolParser::new(&test_tools()); + + let output = collect_stream(&mut parser, &chunks); + + expect![[r#" + ToolParserOutput { + normal_text: "Here goes the bbox call: \n Now the stock price call: \n Now another bbox call: \n See? I'm a helpful assistant.", + calls: [ + ToolCallDelta { + tool_index: 0, + name: Some( + "find_bbox", + ), + arguments: "{\"coordinates\": [[23.54, 43.1], [-12.2, 54.3], [4, 5]], \"coordinate_type\": \"latlong\"}", + }, + ToolCallDelta { + tool_index: 1, + name: Some( + "get_stock_price", + ), + arguments: "{\"symbol\": \"AAPL\", \"start_date\": \"2021-01-01\", \"end_date\": \"2021-12-31\"}", + }, + ToolCallDelta { + tool_index: 2, + name: Some( + "find_bbox", + ), + arguments: "{\"coordinates\": [[23.54, 43.1], [-12.2, 54.3], [4, 5]], \"coordinate_type\": \"latlong\"}", + }, + ], + } + "#]].assert_debug_eq(&output); + } + + #[test] + fn granite4_finish_fails_incomplete_tool_call() { + let mut parser = Granite4ToolParser::new(&test_tools()); + parser + .parse_chunk(r#"{"name":"get_weather","arguments":{"city""#) + .unwrap(); + + let error = parser.finish().unwrap_err(); + + expect!["tool parser parsing failed: incomplete Granite4 tool call"] + .assert_eq(&error.to_report_string()); + } + + #[test] + fn granite4_rejects_non_object_non_string_args() { + let mut parser = Granite4ToolParser::new(&test_tools()); + let error = parser + .parse_chunk(r#"{"name":"f","arguments":42}"#) + .unwrap_err(); + + expect!["tool parser parsing failed: invalid Granite4 arguments"] + .assert_eq(&error.to_report_string()); + } + + #[test] + fn granite4_preserve_special_tokens_is_false() { + let parser = Granite4ToolParser::new(&test_tools()); + assert!(!parser.preserve_special_tokens()); + } +} diff --git a/rust/src/tool-parser/src/json/mod.rs b/rust/src/tool-parser/src/json/mod.rs index 9cc1d2ed543d..748f7e49e4d6 100644 --- a/rust/src/tool-parser/src/json/mod.rs +++ b/rust/src/tool-parser/src/json/mod.rs @@ -1,5 +1,6 @@ //! Shared parser core for JSON tool calls wrapped by text markers. +pub use granite4::Granite4ToolParser; pub use hermes::HermesToolParser; pub use internlm2::Internlm2ToolParser; pub use llama::Llama3JsonToolParser; @@ -7,6 +8,7 @@ pub use mistral::MistralToolParser; pub use phi4mini::Phi4MiniJsonToolParser; pub use qwen::Qwen3XmlToolParser; +mod granite4; mod hermes; mod internlm2; mod llama; diff --git a/rust/src/tool-parser/src/lib.rs b/rust/src/tool-parser/src/lib.rs index 6e77af7bcfbf..b5f0b80d0452 100644 --- a/rust/src/tool-parser/src/lib.rs +++ b/rust/src/tool-parser/src/lib.rs @@ -10,6 +10,7 @@ mod hy_v3; mod json; mod kimi_k2; mod minimax_m2; +mod minimax_m3; mod parameters; mod qwen_coder; #[cfg(any(test, feature = "test-util"))] @@ -25,11 +26,12 @@ pub use gemma4::Gemma4ToolParser; pub use glm_xml::{Glm45MoeToolParser, Glm47MoeToolParser}; pub use hy_v3::HyV3ToolParser; pub use json::{ - HermesToolParser, Internlm2ToolParser, Llama3JsonToolParser, MistralToolParser, - Phi4MiniJsonToolParser, Qwen3XmlToolParser, + Granite4ToolParser, HermesToolParser, Internlm2ToolParser, Llama3JsonToolParser, + MistralToolParser, Phi4MiniJsonToolParser, Qwen3XmlToolParser, }; pub use kimi_k2::KimiK2ToolParser; pub use minimax_m2::MinimaxM2ToolParser; +pub use minimax_m3::MinimaxM3ToolParser; pub use qwen_coder::Qwen3CoderToolParser; use serde::{Deserialize, Serialize}; use serde_json::Value; diff --git a/rust/src/tool-parser/src/minimax_m2.rs b/rust/src/tool-parser/src/minimax_m2.rs index 4cd371740c56..1d7bc78987db 100644 --- a/rust/src/tool-parser/src/minimax_m2.rs +++ b/rust/src/tool-parser/src/minimax_m2.rs @@ -5,7 +5,7 @@ use winnow::stream::Partial; use winnow::token::{literal, rest, take_until}; use super::parameters::ToolSchemas; -use super::utils::{parse_buffered_event, safe_text_len}; +use super::utils::{MarkerScanState, parse_buffered_event, safe_text_len, take_until_marker}; use super::{Result, ToolCallDelta, ToolParser, ToolParserOutput}; use crate::Tool; @@ -18,10 +18,10 @@ const PARAMETER_END: &str = ""; type MinimaxM2Input<'i> = Partial<&'i str>; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] enum MinimaxM2Mode { Text, - ToolBlock, + ToolBlock { invoke_end_scan: MarkerScanState }, Done, } @@ -74,7 +74,11 @@ impl MinimaxM2ToolParser { MinimaxM2Event::Text { len: consumed_len } => { output.normal_text.push_str(&self.buffer[..consumed_len]); } - MinimaxM2Event::ToolBlockStart => self.mode = MinimaxM2Mode::ToolBlock, + MinimaxM2Event::ToolBlockStart => { + self.mode = MinimaxM2Mode::ToolBlock { + invoke_end_scan: MarkerScanState::default(), + }; + } MinimaxM2Event::Invoke { name, raw_params } => { let arguments = self.tool_parameters.convert_params_with_schema(&name, raw_params); let arguments = serde_json::to_string(&arguments) @@ -112,7 +116,7 @@ impl ToolParser for MinimaxM2ToolParser { self.buffer.push_str(chunk); while let Some((event, consumed_len)) = parse_buffered_event(&self.buffer, |input| { - parse_next_minimax_m2_event(input, self.mode) + parse_next_minimax_m2_event(input, &mut self.mode) })? { self.apply_event(event, output)?; self.buffer.drain(..consumed_len); @@ -127,7 +131,7 @@ impl ToolParser for MinimaxM2ToolParser { MinimaxM2Mode::Text => { output.normal_text.push_str(&self.buffer); } - MinimaxM2Mode::ToolBlock => { + MinimaxM2Mode::ToolBlock { .. } => { return Err(parsing_failed!("incomplete MiniMax M2 tool call")); } MinimaxM2Mode::Done => {} @@ -144,11 +148,13 @@ impl ToolParser for MinimaxM2ToolParser { /// Parse a MiniMax M2 event for the current parser mode. fn parse_next_minimax_m2_event( input: &mut MinimaxM2Input<'_>, - mode: MinimaxM2Mode, + mode: &mut MinimaxM2Mode, ) -> ModalResult { match mode { MinimaxM2Mode::Text => parse_text_event(input), - MinimaxM2Mode::ToolBlock => parse_tool_block_event(input), + MinimaxM2Mode::ToolBlock { invoke_end_scan } => { + parse_tool_block_event(input, invoke_end_scan) + } MinimaxM2Mode::Done => ignored_rest_event(input), } } @@ -169,8 +175,14 @@ fn safe_text_event(input: &mut MinimaxM2Input<'_>) -> ModalResult) -> ModalResult { - alt((tool_block_end_event, invoke_event)).parse_next(input) +fn parse_tool_block_event( + input: &mut MinimaxM2Input<'_>, + invoke_end_scan: &mut MarkerScanState, +) -> ModalResult { + alt((tool_block_end_event, |input: &mut MinimaxM2Input<'_>| { + invoke_event(input, invoke_end_scan) + })) + .parse_next(input) } /// Parse a MiniMax M2 tool-block end marker. @@ -181,14 +193,17 @@ fn tool_block_end_event(input: &mut MinimaxM2Input<'_>) -> ModalResult) -> ModalResult { +fn invoke_event( + input: &mut MinimaxM2Input<'_>, + invoke_end_scan: &mut MarkerScanState, +) -> ModalResult { let (name, body) = seq!( _: ws0, _: literal(INVOKE_START), _: (ws1, literal("name=")), partial_attr_value, _: literal(">"), - take_until(0.., INVOKE_END), + take_until_marker(INVOKE_END, invoke_end_scan), _: literal(INVOKE_END), ) .parse_next(input)?; diff --git a/rust/src/tool-parser/src/minimax_m3.rs b/rust/src/tool-parser/src/minimax_m3.rs new file mode 100644 index 000000000000..ad40a7f18b7f --- /dev/null +++ b/rust/src/tool-parser/src/minimax_m3.rs @@ -0,0 +1,900 @@ +use winnow::ascii::{multispace0 as ws0, multispace1 as ws1}; +use winnow::combinator::{alt, delimited, seq}; +use winnow::error::{ContextError, ErrMode}; +use winnow::prelude::*; +use winnow::stream::Partial; +use winnow::token::{literal, rest, take_until}; + +use super::parameters::{ParamElement, ParamInput, ToolSchemas}; +use super::utils::{MarkerScanState, parse_buffered_event, safe_text_len, take_until_marker}; +use super::{Result, ToolCallDelta, ToolParser, ToolParserOutput}; +use crate::Tool; + +const NAMESPACE: &str = "]<]minimax[>["; +const TOOL_CALL_START: &str = "]<]minimax[>["; +const TOOL_CALL_END: &str = "]<]minimax[>["; +const INVOKE_START: &str = "]<]minimax[>[ = Partial<&'i str>; + +#[derive(Debug, Clone, PartialEq, Eq)] +enum MinimaxM3Mode { + Text, + ToolBlock { invoke_end_scan: MarkerScanState }, + Done, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum MinimaxM3Event { + Text { + len: usize, + }, + ToolBlockStart, + Invoke { + name: String, + params: Vec<(String, ParamInput)>, + }, + ToolBlockEnd, + IgnoredRest, +} + +/// Tool parser for MiniMax M3 namespace-delimited XML-style tool calls. +/// +/// Example tool call content with recursive parameters: +/// +/// ```text +/// ]<]minimax[>[ +/// ]<]minimax[>[ +/// ]<]minimax[>[42]<]minimax[>[ +/// ]<]minimax[>[ +/// ]<]minimax[>[Singapore]<]minimax[>[ +/// ]<]minimax[>[018956]<]minimax[>[ +/// ]<]minimax[>[ +/// ]<]minimax[>[ +/// ]<]minimax[>[ +/// ]<]minimax[>[book-001]<]minimax[>[ +/// ]<]minimax[>[2]<]minimax[>[ +/// ]<]minimax[>[ +/// ]<]minimax[>[ +/// ]<]minimax[>[ +/// ]<]minimax[>[ +/// ``` +/// +/// With a schema where `shipping` is an object and `items` is an array of +/// objects, recursive parameter conversion produces: +/// +/// ```json +/// { +/// "user_id": 42, +/// "shipping": { +/// "city": "Singapore", +/// "zip": 18956 +/// }, +/// "items": [ +/// { +/// "sku": "book-001", +/// "qty": 2 +/// } +/// ] +/// } +/// ``` +/// +/// MiniMax M3 emits the namespace marker `]<]minimax[>[` before each structural +/// tag. Arguments are emitted only after a full `` block is parsed. +pub struct MinimaxM3ToolParser { + buffer: String, + mode: MinimaxM3Mode, + emitted_tool_count: usize, + tool_parameters: ToolSchemas, +} + +impl MinimaxM3ToolParser { + /// Create a MiniMax M3 tool parser. + pub fn new(tools: &[Tool]) -> Self { + Self { + buffer: String::new(), + mode: MinimaxM3Mode::Text, + emitted_tool_count: 0, + tool_parameters: ToolSchemas::from_tools(tools), + } + } + + /// Apply one parsed MiniMax M3 event to parser state and output. + fn apply_event(&mut self, event: MinimaxM3Event, output: &mut ToolParserOutput) -> Result<()> { + match event { + MinimaxM3Event::Text { len: consumed_len } => { + output.normal_text.push_str(&self.buffer[..consumed_len]); + } + MinimaxM3Event::ToolBlockStart => { + self.mode = MinimaxM3Mode::ToolBlock { + invoke_end_scan: MarkerScanState::default(), + }; + } + MinimaxM3Event::Invoke { name, params } => { + let arguments = self.tool_parameters.convert_params_with_schema(&name, params); + let arguments = serde_json::to_string(&arguments) + .map_err(|error| parsing_failed!("failed to serialize arguments: {}", error))?; + + output.calls.push(ToolCallDelta { + tool_index: self.emitted_tool_count, + name: Some(name), + arguments, + }); + self.emitted_tool_count += 1; + } + MinimaxM3Event::ToolBlockEnd => self.mode = MinimaxM3Mode::Done, + MinimaxM3Event::IgnoredRest => {} + } + Ok(()) + } +} + +impl ToolParser for MinimaxM3ToolParser { + fn create(tools: &[Tool]) -> Result> + where + Self: Sized + 'static, + { + Ok(Box::new(Self::new(tools))) + } + + fn parse_into(&mut self, chunk: &str, output: &mut ToolParserOutput) -> Result<()> { + self.buffer.push_str(chunk); + + while let Some((event, consumed_len)) = parse_buffered_event(&self.buffer, |input| { + parse_next_minimax_m3_event(input, &mut self.mode) + })? { + self.apply_event(event, output)?; + self.buffer.drain(..consumed_len); + } + + Ok(()) + } + + fn finish(&mut self) -> Result { + let mut output = ToolParserOutput::default(); + match self.mode { + MinimaxM3Mode::Text => { + output.normal_text.push_str(&self.buffer); + } + MinimaxM3Mode::ToolBlock { .. } => { + if !self.buffer.trim_start().is_empty() { + return Err(parsing_failed!("incomplete MiniMax M3 tool call")); + } + } + MinimaxM3Mode::Done => {} + } + let _ = self.reset(); + Ok(output) + } + + fn reset(&mut self) -> String { + self.mode = MinimaxM3Mode::Text; + self.emitted_tool_count = 0; + std::mem::take(&mut self.buffer) + } +} + +/// Parse a MiniMax M3 event for the current parser mode. +fn parse_next_minimax_m3_event( + input: &mut MinimaxM3Input<'_>, + mode: &mut MinimaxM3Mode, +) -> ModalResult { + match mode { + MinimaxM3Mode::Text => parse_text_event(input), + MinimaxM3Mode::ToolBlock { invoke_end_scan } => { + parse_tool_block_event(input, invoke_end_scan) + } + MinimaxM3Mode::Done => ignored_rest_event(input), + } +} + +/// Parse a text-mode MiniMax M3 event. +fn parse_text_event(input: &mut MinimaxM3Input<'_>) -> ModalResult { + alt((tool_block_start_event, safe_text_event)).parse_next(input) +} + +/// Parse a MiniMax M3 tool-block start marker. +fn tool_block_start_event(input: &mut MinimaxM3Input<'_>) -> ModalResult { + literal(TOOL_CALL_START).value(MinimaxM3Event::ToolBlockStart).parse_next(input) +} + +/// Parse a safe text run before the next MiniMax M3 marker. +fn safe_text_event(input: &mut MinimaxM3Input<'_>) -> ModalResult { + safe_text_len(input, TOOL_CALL_START).map(|len| MinimaxM3Event::Text { len }) +} + +/// Parse one event inside a MiniMax M3 tool block. +fn parse_tool_block_event( + input: &mut MinimaxM3Input<'_>, + invoke_end_scan: &mut MarkerScanState, +) -> ModalResult { + alt((tool_block_end_event, |input: &mut MinimaxM3Input<'_>| { + invoke_event(input, invoke_end_scan) + })) + .parse_next(input) +} + +/// Parse a MiniMax M3 tool-block end marker. +fn tool_block_end_event(input: &mut MinimaxM3Input<'_>) -> ModalResult { + (ws0, literal(TOOL_CALL_END)) + .value(MinimaxM3Event::ToolBlockEnd) + .parse_next(input) +} + +/// Parse a complete MiniMax M3 invoke block. +fn invoke_event( + input: &mut MinimaxM3Input<'_>, + invoke_end_scan: &mut MarkerScanState, +) -> ModalResult { + let (name, body) = seq!( + _: ws0, + _: literal(INVOKE_START), + _: (ws1, literal("name=")), + partial_attr_value, + _: literal(">"), + take_until_marker(INVOKE_END, invoke_end_scan), + _: literal(INVOKE_END), + ) + .parse_next(input)?; + let params = parse_invoke_params(body)?; + + Ok(MinimaxM3Event::Invoke { + name: name.trim().to_string(), + params, + }) +} + +/// Parse all parameter elements inside a complete MiniMax M3 invoke body. +fn parse_invoke_params(invoke_body: &str) -> ModalResult> { + let mut input = invoke_body; + let mut elements = Vec::new(); + + loop { + let _ = ws0.parse_next(&mut input)?; + if input.is_empty() { + break; + } + if input.starts_with(ELEMENT_START) { + elements.push(parameter_element(&mut input)?); + continue; + } + if input.starts_with(NAMESPACE) { + return malformed(); + } + // Be tolerant: ordinary text at an invokeparameter boundary ends this invoke. + // Keep parsed parameters and drop the remaining invoke body. + break; + } + + Ok(elements.into_iter().map(|element| (element.name, element.value)).collect()) +} + +/// Parse a MiniMax M3 parameter element. +fn parameter_element(input: &mut &str) -> ModalResult { + let name = open_element_tag(input)?.to_string(); + let value = element_body(input, &name)?; + close_element_tag(input, &name)?; + Ok(ParamElement { name, value }) +} + +/// Parse a MiniMax M3 opening element tag. +fn open_element_tag<'i>(input: &mut &'i str) -> ModalResult<&'i str> { + let name = seq!( + _: literal(ELEMENT_START), + take_until(1.., ">"), + _: literal(">"), + ) + .parse_next(input)?; + + let name = name.0; + if name.starts_with('/') || name.trim().is_empty() { + return malformed(); + } + + Ok(name) +} + +/// Parse a MiniMax M3 closing element tag. +fn close_element_tag(input: &mut &str, name: &str) -> ModalResult<()> { + literal(ELEMENT_END_START).void().parse_next(input)?; + literal(name).void().parse_next(input)?; + literal(">").void().parse_next(input) +} + +/// Parse the body of one MiniMax M3 element. +fn element_body(input: &mut &str, closing_name: &str) -> ModalResult { + let close_tag = format!("{ELEMENT_END_START}{closing_name}>"); + let mut text = String::new(); + let mut elements = Vec::new(); + + loop { + text.push_str(text_until_namespace(input)?); + + if input.starts_with(&close_tag) { + // Close tag reached, end of element body. + break; + } + if input.starts_with(ELEMENT_START) { + // Child element start reached, parse child element recursively. + elements.push(parameter_element(input)?); + continue; + } + if input.starts_with(NAMESPACE) { + // Unexpected namespace marker. + return malformed(); + } + } + + if elements.is_empty() { + Ok(ParamInput::Text(text)) + } else { + if !text.trim().is_empty() { + push_mixed_text_element(&mut elements, text); + } + Ok(ParamInput::Elements(elements)) + } +} + +/// Parse text until the next MiniMax M3 namespace marker. +fn text_until_namespace<'i>(input: &mut &'i str) -> ModalResult<&'i str> { + take_until(0.., NAMESPACE).parse_next(input) +} + +/// Preserve mixed text content under a reserved object field. +/// +/// By default, the field name is `$text`, but if that collides with an existing +/// child element name, prepend `$` until there is no collision. +fn push_mixed_text_element(elements: &mut Vec, text: String) { + let mut name = MIXED_TEXT_FIELD.to_string(); + while elements.iter().any(|element| element.name == name) { + name.insert(0, '$'); + } + elements.push(ParamElement { + name, + value: ParamInput::Text(text), + }); +} + +/// Parse a quoted or unquoted XML attribute value from partial streaming input. +fn partial_attr_value<'i>(input: &mut MinimaxM3Input<'i>) -> ModalResult<&'i str> { + alt(( + delimited(literal("\""), take_until(1.., "\""), literal("\"")), + delimited(literal("'"), take_until(1.., "'"), literal("'")), + take_until(1.., ">"), + )) + .parse_next(input) +} + +/// Parse ignored rest after the MiniMax M3 tool block ends. +fn ignored_rest_event(input: &mut MinimaxM3Input<'_>) -> ModalResult { + rest.value(MinimaxM3Event::IgnoredRest).parse_next(input) +} + +fn malformed() -> ModalResult { + Err(ErrMode::Cut(ContextError::new())) +} + +#[cfg(test)] +mod tests { + use expect_test::expect; + use serde_json::{Value, json}; + use thiserror_ext::AsReport; + + use super::{ + ELEMENT_END_START, ELEMENT_START, INVOKE_END, INVOKE_START, MinimaxM3ToolParser, + TOOL_CALL_END, TOOL_CALL_START, ToolParser, + }; + use crate::test_utils::{collect_stream, split_by_chars, test_tools}; + use crate::{Tool, ToolParserTestExt as _}; + + fn element(name: &str, body: &str) -> String { + format!("{ELEMENT_START}{name}>{body}{ELEMENT_END_START}{name}>") + } + + fn invoke(function_name: &str, body: &str) -> String { + format!("{INVOKE_START} name=\"{function_name}\">{body}{INVOKE_END}") + } + + fn build_tool_block(invokes: &[(&str, String)]) -> String { + let invokes = invokes + .iter() + .map(|(function_name, body)| invoke(function_name, body)) + .collect::>() + .join("\n"); + format!("{TOOL_CALL_START}\n{invokes}\n{TOOL_CALL_END}") + } + + fn m3_test_tools() -> Vec { + let mut tools = test_tools(); + tools.push(Tool { + name: "create_order".to_string(), + description: None, + parameters: json!({ + "type": "object", + "properties": { + "user_id": { "type": "integer" }, + "urgent": { "type": "boolean" }, + "note": { "type": "string" }, + "shipping": { + "type": "object", + "properties": { + "city": { "type": "string" }, + "zip": { "type": "integer" } + } + }, + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "sku": { "type": "string" }, + "qty": { "type": "integer" } + } + } + }, + "metadata": { + "type": "object", + "additionalProperties": { "type": "integer" } + }, + "duplicate_demo": { + "type": "object", + "properties": { + "tag": { "type": "string" } + } + }, + "schema_mismatch_array": { + "type": "array", + "items": { "type": "integer" } + } + } + }), + strict: None, + }); + tools + } + + fn order_arguments() -> String { + let shipping = element( + "shipping", + &format!( + "{}{}", + element("city", "Singapore"), + element("zip", "018956") + ), + ); + let first_item = element( + "item", + &format!("{}{}", element("sku", "book-001"), element("qty", "2")), + ); + let second_item = element( + "item", + &format!("{}{}", element("sku", "pen-007"), element("qty", "5")), + ); + let items = element("items", &format!("{first_item}{second_item}")); + let metadata = element( + "metadata", + &format!("{}{}", element("score", "42"), element("rank", "7")), + ); + let duplicate_demo = element( + "duplicate_demo", + &format!("{}{}", element("tag", "a"), element("tag", "b")), + ); + let schema_mismatch_array = element( + "schema_mismatch_array", + &format!("{}{}", element("x", "1"), element("x", "2")), + ); + + [ + element("user_id", "42"), + element("urgent", "true"), + element("note", "Please leave at front desk."), + shipping, + items, + metadata, + duplicate_demo, + schema_mismatch_array, + element( + "unknown_struct", + &format!("{}{}", element("a", "1"), element("a", "2")), + ), + ] + .join("") + } + + #[test] + fn minimax_m3_parse_complete_without_tool_call_keeps_text() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = parser.parse_complete("Hello, world!").unwrap(); + + assert_eq!(output.normal_text, "Hello, world!"); + assert!(output.calls.is_empty()); + } + + #[test] + fn minimax_m3_parse_complete_extracts_single_tool_call() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = parser + .parse_complete(&build_tool_block(&[( + "get_weather", + format!("{}{}", element("city", "Seattle"), element("days", "5")), + )])) + .unwrap(); + + assert!(output.normal_text.is_empty()); + assert_eq!(output.calls.len(), 1); + assert_eq!(output.calls[0].name.as_deref(), Some("get_weather")); + assert_eq!( + serde_json::from_str::(&output.calls[0].arguments).unwrap(), + json!({ "city": "Seattle", "days": 5 }) + ); + } + + #[test] + fn minimax_m3_parse_complete_preserves_prefix_and_ignores_trailing_text() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = format!( + "Let me check. {} This trailing text is ignored.", + build_tool_block(&[("get_weather", element("city", "Seattle"))]) + ); + let output = parser.parse_complete(&output).unwrap(); + + assert_eq!(output.normal_text, "Let me check. "); + assert_eq!(output.calls.len(), 1); + } + + #[test] + fn minimax_m3_parse_complete_extracts_multiple_invokes() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = parser + .parse_complete(&build_tool_block(&[ + ("get_weather", element("city", "Seattle")), + ("get_weather", element("city", "NYC")), + ])) + .unwrap(); + + assert_eq!(output.calls.len(), 2); + assert_eq!(output.calls[0].tool_index, 0); + assert_eq!(output.calls[1].tool_index, 1); + assert_eq!( + serde_json::from_str::(&output.calls[0].arguments).unwrap(), + json!({ "city": "Seattle" }) + ); + assert_eq!( + serde_json::from_str::(&output.calls[1].arguments).unwrap(), + json!({ "city": "NYC" }) + ); + } + + #[test] + fn minimax_m3_invoke_body_junk_drops_rest_of_invoke() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = parser + .parse_complete(&build_tool_block(&[( + "get_weather", + [ + element("city", "Seattle"), + "I need to use the city above.".to_string(), + element("days", "5"), + ] + .join(""), + )])) + .unwrap(); + + assert_eq!( + serde_json::from_str::(&output.calls[0].arguments).unwrap(), + json!({ "city": "Seattle" }) + ); + } + + #[test] + fn minimax_m3_parse_complete_converts_schema_types() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = parser + .parse_complete(&build_tool_block(&[( + "convert", + [ + element("whole", "5.0"), + element("flag", "true"), + element("payload", r#"{"nested":true}"#), + element("items", "[1,2]"), + element("empty", "42"), + ] + .join(""), + )])) + .unwrap(); + + assert_eq!( + serde_json::from_str::(&output.calls[0].arguments).unwrap(), + json!({ + "whole": 5.0, + "flag": true, + "payload": { "nested": true }, + "items": [1, 2], + "empty": "42", + }) + ); + } + + #[test] + fn minimax_m3_parse_complete_converts_nested_arguments() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = parser + .parse_complete(&build_tool_block(&[("create_order", order_arguments())])) + .unwrap(); + + assert_eq!( + serde_json::from_str::(&output.calls[0].arguments).unwrap(), + json!({ + "user_id": 42, + "urgent": true, + "note": "Please leave at front desk.", + "shipping": { + "city": "Singapore", + "zip": 18956 + }, + "items": [ + { + "sku": "book-001", + "qty": 2 + }, + { + "sku": "pen-007", + "qty": 5 + } + ], + "metadata": { + "score": 42, + "rank": 7 + }, + "duplicate_demo": { + "tag": ["a", "b"] + }, + "schema_mismatch_array": [1, 2], + "unknown_struct": { + "a": ["1", "2"] + } + }) + ); + } + + #[test] + fn minimax_m3_parse_complete_handles_multiline_leaf_parameters() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = parser + .parse_complete(&build_tool_block(&[( + "calculate_area", + [ + element("shape", "\nrectangle\n"), + element("dimensions", r#"{"width":10,"height":20}"#), + element("precision", "2"), + ] + .join(""), + )])) + .unwrap(); + + assert_eq!( + serde_json::from_str::(&output.calls[0].arguments).unwrap(), + json!({ + "shape": "\nrectangle\n", + "dimensions": { "width": 10, "height": 20 }, + "precision": 2, + }) + ); + } + + #[test] + fn minimax_m3_streaming_extracts_single_tool_call() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = collect_stream( + &mut parser, + &[ + TOOL_CALL_START, + &invoke("get_weather", &element("city", "Seattle")), + TOOL_CALL_END, + ], + ); + + assert!(output.normal_text.is_empty()); + assert_eq!(output.calls.len(), 1); + assert_eq!(output.calls[0].name.as_deref(), Some("get_weather")); + assert_eq!( + serde_json::from_str::(&output.calls[0].arguments).unwrap(), + json!({ "city": "Seattle" }) + ); + } + + #[test] + fn minimax_m3_streaming_preserves_prefix_text() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = collect_stream( + &mut parser, + &[ + "Let me check. ", + TOOL_CALL_START, + &invoke("get_weather", &element("city", "Seattle")), + TOOL_CALL_END, + ], + ); + + assert_eq!(output.normal_text, "Let me check. "); + assert_eq!(output.calls.len(), 1); + } + + #[test] + fn minimax_m3_streaming_without_tool_call_emits_text_incrementally() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = collect_stream(&mut parser, &["Hello, ", "world!"]); + + assert_eq!(output.normal_text, "Hello, world!"); + assert!(output.calls.is_empty()); + } + + #[test] + fn minimax_m3_streaming_handles_marker_split_across_chunks() { + let text = build_tool_block(&[("get_weather", element("city", "Seattle"))]); + let chunks = split_by_chars(&text, 3); + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = collect_stream(&mut parser, &chunks); + + assert_eq!(output.calls.len(), 1); + assert!(output.normal_text.is_empty()); + } + + #[test] + fn minimax_m3_streaming_extracts_multiple_invokes_in_order() { + let text = build_tool_block(&[ + ("get_weather", element("city", "Seattle")), + ("get_weather", element("city", "NYC")), + ]); + let chunks = split_by_chars(&text, 7); + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = collect_stream(&mut parser, &chunks); + + assert_eq!(output.calls.len(), 2); + assert_eq!(output.calls[0].tool_index, 0); + assert_eq!(output.calls[1].tool_index, 1); + } + + #[test] + fn minimax_m3_streaming_does_not_emit_incomplete_tool_call() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = parser + .parse_chunk(&format!( + "{TOOL_CALL_START}{INVOKE_START} name=\"get_weather\">" + )) + .unwrap(); + + assert!(output.normal_text.is_empty()); + assert!(output.calls.is_empty()); + } + + #[test] + fn minimax_m3_streaming_ignores_text_after_tool_block() { + let text = format!( + "{} ignored", + build_tool_block(&[("get_weather", element("city", "Seattle"))]) + ); + let chunks = split_by_chars(&text, 5); + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = collect_stream(&mut parser, &chunks); + + assert!(output.normal_text.is_empty()); + assert_eq!(output.calls.len(), 1); + } + + #[test] + fn minimax_m3_finish_fails_incomplete_tool_call() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + parser + .parse_chunk(&format!( + "{TOOL_CALL_START}{INVOKE_START} name=\"get_weather\">" + )) + .unwrap(); + + assert!(parser.finish().is_err()); + } + + #[test] + fn minimax_m3_finish_recovers_after_bare_tool_block_start() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + parser.parse_chunk(TOOL_CALL_START).unwrap(); + + let output = parser.finish().unwrap(); + assert!(output.normal_text.is_empty()); + assert!(output.calls.is_empty()); + } + + #[test] + fn minimax_m3_finish_recovers_completed_invoke_with_whitespace_tail() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let output = parser + .parse_complete(&format!( + "{}\n{}\n \n", + TOOL_CALL_START, + invoke("get_weather", &element("city", "Seattle")) + )) + .unwrap(); + + assert_eq!(output.calls.len(), 1); + assert_eq!( + serde_json::from_str::(&output.calls[0].arguments).unwrap(), + json!({ "city": "Seattle" }) + ); + } + + #[test] + fn minimax_m3_finish_fails_partial_outer_end_marker() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + parser + .parse_chunk(&format!( + "{}\n{}\n{}", + TOOL_CALL_START, + invoke("get_weather", &element("city", "Seattle")), + &TOOL_CALL_END[..3] + )) + .unwrap(); + + assert!(parser.finish().is_err()); + } + + #[test] + fn minimax_m3_malformed_tool_call_fails_fast() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let error = parser + .parse_chunk(&format!( + "{TOOL_CALL_START}{ELEMENT_START}bad>{TOOL_CALL_END}" + )) + .unwrap_err(); + + expect!["tool parser parsing failed: "].assert_eq(&error.to_report_string()); + } + + #[test] + fn minimax_m3_mixed_content_is_preserved_as_text_field() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let body = element( + "payload", + &format!("text before {} text after", element("child", "value")), + ); + let output = parser.parse_complete(&build_tool_block(&[("convert", body)])).unwrap(); + + assert_eq!( + serde_json::from_str::(&output.calls[0].arguments).unwrap(), + json!({ + "payload": { + "child": "value", + "$text": "text before text after" + } + }) + ); + } + + #[test] + fn minimax_m3_mixed_text_field_avoids_child_name_collision() { + let mut parser = MinimaxM3ToolParser::new(&m3_test_tools()); + let body = element( + "payload", + &format!( + "text{}{}", + element("$text", "child text"), + element("child", "value") + ), + ); + let output = parser.parse_complete(&build_tool_block(&[("convert", body)])).unwrap(); + + assert_eq!( + serde_json::from_str::(&output.calls[0].arguments).unwrap(), + json!({ + "payload": { + "$text": "child text", + "$$text": "text", + "child": "value" + } + }) + ); + } +} diff --git a/rust/src/tool-parser/src/qwen_coder.rs b/rust/src/tool-parser/src/qwen_coder.rs index 0a2bcd41611d..270955aff076 100644 --- a/rust/src/tool-parser/src/qwen_coder.rs +++ b/rust/src/tool-parser/src/qwen_coder.rs @@ -5,7 +5,7 @@ use winnow::stream::Partial; use winnow::token::{literal, take_until}; use super::parameters::ToolSchemas; -use super::utils::{parse_buffered_event, safe_text_len}; +use super::utils::{MarkerScanState, parse_buffered_event, safe_text_len, take_until_marker}; use super::{Result, ToolCallDelta, ToolParser, ToolParserOutput}; use crate::Tool; @@ -18,10 +18,10 @@ const PARAMETER_END: &str = ""; type QwenCoderInput<'i> = Partial<&'i str>; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] enum QwenCoderMode { Text, - ToolCall, + ToolCall { end_marker_scan: MarkerScanState }, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -76,7 +76,11 @@ impl Qwen3CoderToolParser { QwenCoderEvent::Text { len: consumed_len } => { output.normal_text.push_str(&self.buffer[..consumed_len]); } - QwenCoderEvent::ToolCallStart => self.mode = QwenCoderMode::ToolCall, + QwenCoderEvent::ToolCallStart => { + self.mode = QwenCoderMode::ToolCall { + end_marker_scan: MarkerScanState::default(), + }; + } QwenCoderEvent::ToolCall { name, raw_params } => { self.mode = QwenCoderMode::Text; let arguments = self.tool_parameters.convert_params_with_schema(&name, raw_params); @@ -113,7 +117,7 @@ impl ToolParser for Qwen3CoderToolParser { self.buffer.push_str(chunk); while let Some((event, consumed_len)) = parse_buffered_event(&self.buffer, |input| { - parse_next_qwen_coder_event(input, self.mode) + parse_next_qwen_coder_event(input, &mut self.mode) })? { self.apply_event(event, output)?; self.buffer.drain(..consumed_len); @@ -125,7 +129,9 @@ impl ToolParser for Qwen3CoderToolParser { fn finish(&mut self) -> Result { let mut output = ToolParserOutput::default(); if !self.buffer.is_empty() { - if self.mode == QwenCoderMode::ToolCall || self.buffer.starts_with(TOOL_CALL_START) { + if matches!(self.mode, QwenCoderMode::ToolCall { .. }) + || self.buffer.starts_with(TOOL_CALL_START) + { return Err(parsing_failed!("incomplete Qwen Coder tool call")); } output.normal_text.push_str(&self.buffer); @@ -142,11 +148,11 @@ impl ToolParser for Qwen3CoderToolParser { /// Parse a Qwen Coder event for the current parser mode. fn parse_next_qwen_coder_event( input: &mut QwenCoderInput<'_>, - mode: QwenCoderMode, + mode: &mut QwenCoderMode, ) -> ModalResult { match mode { QwenCoderMode::Text => parse_text_event(input), - QwenCoderMode::ToolCall => tool_call_event(input), + QwenCoderMode::ToolCall { end_marker_scan } => tool_call_event(input, end_marker_scan), } } @@ -166,10 +172,13 @@ fn safe_text_event(input: &mut QwenCoderInput<'_>) -> ModalResult) -> ModalResult { +fn tool_call_event( + input: &mut QwenCoderInput<'_>, + end_marker_scan: &mut MarkerScanState, +) -> ModalResult { let (body,) = seq!( _: ws0, - take_until(0.., TOOL_CALL_END), + take_until_marker(TOOL_CALL_END, end_marker_scan), _: literal(TOOL_CALL_END), ) .parse_next(input)?; @@ -228,8 +237,8 @@ mod tests { use thiserror_ext::AsReport; use super::{Qwen3CoderToolParser, ToolParser}; - use crate::ToolParserTestExt as _; use crate::test_utils::{collect_stream, split_by_chars, test_tools}; + use crate::{ToolParserOutput, ToolParserTestExt as _}; fn build_tool_call(function_name: &str, params: &[(&str, &str)]) -> String { let params = params @@ -574,6 +583,68 @@ mod tests { ); } + #[test] + fn qwen_coder_streaming_handles_end_token_split_across_chunks() { + let mut parser = Qwen3CoderToolParser::new(&test_tools()); + let output = parser + .parse_chunk( + "\n\ + \n\ + SF\n\ + \n\ + ").unwrap()); + output.append(parser.finish().unwrap()); + let output = output.coalesce_calls(); + + assert!(output.normal_text.is_empty()); + assert_eq!(output.calls.len(), 1); + assert_eq!(output.calls[0].name.as_deref(), Some("get_weather")); + assert_eq!( + serde_json::from_str::(&output.calls[0].arguments).unwrap(), + json!({ "location": "SF" }) + ); + } + + #[test] + fn qwen_coder_streaming_buffers_long_body_until_end_marker() { + let long_location = format!("SF-{}", "x".repeat(8192)); + let text = build_tool_call("get_weather", &[("location", &long_location)]); + let split_at = text.len() - "_call>".len(); + let (body_with_partial_end, end_suffix) = text.split_at(split_at); + let chunks = split_by_chars(body_with_partial_end, 31); + let mut parser = Qwen3CoderToolParser::new(&test_tools()); + let mut output = ToolParserOutput::default(); + + assert_eq!(end_suffix, "_call>"); + + for chunk in chunks { + let chunk_output = parser.parse_chunk(chunk).unwrap(); + assert!(chunk_output.normal_text.is_empty()); + assert!(chunk_output.calls.is_empty()); + output.append(chunk_output); + } + + output.append(parser.parse_chunk(end_suffix).unwrap()); + output.append(parser.finish().unwrap()); + let output = output.coalesce_calls(); + + assert!(output.normal_text.is_empty()); + assert_eq!(output.calls.len(), 1); + assert_eq!(output.calls[0].name.as_deref(), Some("get_weather")); + assert_eq!( + serde_json::from_str::(&output.calls[0].arguments).unwrap(), + json!({ "location": long_location }) + ); + } + #[test] fn qwen_coder_streaming_does_not_emit_incomplete_tool_call() { let mut parser = Qwen3CoderToolParser::new(&test_tools()); diff --git a/rust/src/tool-parser/src/utils.rs b/rust/src/tool-parser/src/utils.rs index 544c5d5dcbf3..b545c5881c16 100644 --- a/rust/src/tool-parser/src/utils.rs +++ b/rust/src/tool-parser/src/utils.rs @@ -1,5 +1,6 @@ //! Shared helpers for tool parsers. +use winnow::Parser; use winnow::error::{ContextError, ErrMode, ModalResult, Needed, StrContext, StrContextValue}; use winnow::stream::{Offset, Partial, Stream}; @@ -66,6 +67,74 @@ pub(super) fn safe_text_len(input: &mut Partial<&str>, marker: &str) -> ModalRes Ok(emit_len) } +/// Streaming scan state for a buffered marker search [`take_until_marker`], +/// so that we don't have to rescan the whole buffered prefix when resuming. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(super) struct MarkerScanState { + scan_start: usize, +} + +impl MarkerScanState { + pub(super) fn reset(&mut self) { + self.scan_start = 0; + } +} + +/// Parse text until `marker`, resuming from the last safe scan checkpoint. +/// +/// This is the streaming-buffered variant of `winnow::token::take_until(0.., +/// marker)`: it returns the slice before `marker` and leaves `marker` for the +/// caller to consume. On incomplete input, it stores the earliest byte offset +/// that can still match `marker` and returns `Incomplete` without consuming +/// input, so the next parse can avoid rescanning the whole buffered prefix. +/// +/// Use this for outer parser states that keep the full buffered input across +/// chunks while waiting for a closing marker. Plain `take_until` is still a +/// better fit for one-shot parsers over a complete body, and for `1..` cases +/// where an empty slice before the marker should be rejected. +pub(super) fn take_until_marker<'i, 'a>( + marker: &'a str, + state: &'a mut MarkerScanState, +) -> impl Parser, &'i str, ErrMode> + 'a { + move |input: &mut Partial<&'i str>| take_until_marker_(input, marker, state) +} + +fn take_until_marker_<'i>( + input: &mut Partial<&'i str>, + marker: &str, + state: &mut MarkerScanState, +) -> ModalResult<&'i str> { + debug_assert!(!marker.is_empty()); + + let text = **input; + if text.is_empty() { + return incomplete(); + } + + // Normal updates store a char boundary; this keeps stale or misused state from panicking. + let scan_start = floor_char_boundary(text, state.scan_start); + + if let Some(offset) = text[scan_start..].find(marker) { + let marker_start = scan_start + offset; + let body = &text[..marker_start]; + input.next_slice(marker_start); + state.reset(); + return Ok(body); + } + + let keep_len = partial_prefix_len(text, marker); + state.scan_start = text.len() - keep_len; + incomplete() +} + +fn floor_char_boundary(text: &str, index: usize) -> usize { + let mut index = index.min(text.len()); + while !text.is_char_boundary(index) { + index -= 1; + } + index +} + /// Streaming lexical state for a top-level JSON object. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub(super) struct JsonObjectScanState { @@ -273,11 +342,13 @@ pub(super) fn incomplete() -> ModalResult { mod tests { use expect_test::expect; + use winnow::Parser; use winnow::error::ErrMode; use winnow::stream::{Offset, Partial, Stream}; use super::{ - JsonObjectScanState, json_str, partial_prefix_len, safe_text_len, take_json_object, + JsonObjectScanState, MarkerScanState, json_str, partial_prefix_len, safe_text_len, + take_json_object, take_until_marker, }; #[test] @@ -335,6 +406,103 @@ mod tests { assert!(matches!(error, ErrMode::Incomplete(_))); } + #[test] + fn take_until_marker_stops_before_marker() { + let mut state = MarkerScanState::default(); + let mut input = Partial::new("bodytail"); + let checkpoint = input.checkpoint(); + + let body = take_until_marker("", &mut state).parse_next(&mut input).unwrap(); + + assert_eq!(body, "body"); + assert_eq!(input.offset_from(&checkpoint), "body".len()); + assert_eq!(*input, "tail"); + assert_eq!(state, MarkerScanState::default()); + } + + #[test] + fn take_until_marker_resumes_after_split_marker() { + let mut state = MarkerScanState::default(); + let mut input = Partial::new("body", &mut state) + .parse_next(&mut input) + .unwrap_err(); + + assert!(matches!(error, ErrMode::Incomplete(_))); + assert_eq!(state.scan_start, "body".len()); + + let mut input = Partial::new("bodytail"); + let body = take_until_marker("", &mut state).parse_next(&mut input).unwrap(); + + assert_eq!(body, "body"); + assert_eq!(*input, "tail"); + assert_eq!(state, MarkerScanState::default()); + } + + #[test] + fn take_until_marker_advances_checkpoint_for_long_prefix() { + let mut state = MarkerScanState::default(); + let text = format!("{}{}", "x".repeat(1024), "", &mut state) + .parse_next(&mut input) + .unwrap_err(); + + assert!(matches!(error, ErrMode::Incomplete(_))); + assert_eq!(state.scan_start, 1024); + } + + #[test] + fn take_until_marker_keeps_unicode_marker_boundaries() { + let marker = "<|DSML|function_calls>"; + let mut state = MarkerScanState::default(); + let mut input = Partial::new("prefix <|DSML|fun"); + + let error = take_until_marker(marker, &mut state).parse_next(&mut input).unwrap_err(); + + assert!(matches!(error, ErrMode::Incomplete(_))); + assert_eq!(state.scan_start, "prefix ".len()); + assert!("prefix <|DSML|fun".is_char_boundary(state.scan_start)); + + let mut input = Partial::new("prefix <|DSML|function_calls>tail"); + let body = take_until_marker(marker, &mut state).parse_next(&mut input).unwrap(); + + assert_eq!(body, "prefix "); + assert_eq!(*input, "<|DSML|function_calls>tail"); + assert_eq!(state, MarkerScanState::default()); + } + + #[test] + fn take_until_marker_floors_stale_checkpoint_to_char_boundary() { + let mut state = MarkerScanState { scan_start: 1 }; + let mut input = Partial::new("é"); + + let body = take_until_marker("", &mut state).parse_next(&mut input).unwrap(); + + assert_eq!(body, "é"); + assert_eq!(*input, ""); + assert_eq!(state, MarkerScanState::default()); + } + + #[test] + fn take_until_marker_handles_overlapping_prefixes() { + let mut state = MarkerScanState::default(); + let mut input = Partial::new("xxaba"); + + let error = take_until_marker("ababa", &mut state).parse_next(&mut input).unwrap_err(); + + assert!(matches!(error, ErrMode::Incomplete(_))); + assert_eq!(state.scan_start, 2); + + let mut input = Partial::new("xxababa!"); + let body = take_until_marker("ababa", &mut state).parse_next(&mut input).unwrap(); + + assert_eq!(body, "xx"); + assert_eq!(*input, "ababa!"); + } + #[test] fn take_json_object_consumes_simple_object() { let mut state = JsonObjectScanState::default(); diff --git a/setup.py b/setup.py index 657a65161e7a..2aaa7dfc49c8 100644 --- a/setup.py +++ b/setup.py @@ -432,6 +432,19 @@ def run(self): dirs_exist_ok=True, ) + # copy vendored fmha_sm100 package from build_lib to source tree + # for editable installs + fmha_sm100_build = os.path.join( + self.build_lib, "vllm", "third_party", "fmha_sm100" + ) + if os.path.exists(fmha_sm100_build): + print(f"Copying {fmha_sm100_build} to vllm/third_party/fmha_sm100") + shutil.copytree( + fmha_sm100_build, + "vllm/third_party/fmha_sm100", + dirs_exist_ok=True, + ) + class precompiled_build_ext(build_ext): """Disables extension building when using precompiled binaries.""" @@ -787,6 +800,7 @@ def extract_precompiled_and_patch_package( ) # DeepGEMM: extract all files (.py, .so, .cuh, .h, .hpp, etc.) deep_gemm_regex = re.compile(r"vllm/third_party/deep_gemm/.*") + fmha_sm100_regex = re.compile(r"vllm/third_party/fmha_sm100/.*") file_members = [] for member in wheel.filelist: if member.filename in exact_members: @@ -812,6 +826,7 @@ def extract_precompiled_and_patch_package( or triton_kernels_regex.match(member.filename) or flashmla_regex.match(member.filename) or deep_gemm_regex.match(member.filename) + or fmha_sm100_regex.match(member.filename) ): file_members.append(member) @@ -1120,6 +1135,8 @@ def _read_requirements(filename: str) -> list[str]: # DeepGEMM requires CUDA 12.3+ (SM90/SM100) # Optional since it won't build on unsupported architectures ext_modules.append(CMakeExtension(name="vllm._deep_gemm_C", optional=True)) + # fmha_sm100 is a Python/CuTe-DSL package installed into vllm.third_party. + ext_modules.append(CMakeExtension(name="vllm.fmha_sm100", optional=True)) if _is_cpu(): import platform @@ -1150,6 +1167,8 @@ def _read_requirements(filename: str) -> list[str]: "third_party/deep_gemm/include/**/*.cuh", "third_party/deep_gemm/include/**/*.h", "third_party/deep_gemm/include/**/*.hpp", + # fmha_sm100 sparse CuTe-DSL helper kernels (vendored via cmake) + "third_party/fmha_sm100/cute/**/*.cu", ] } @@ -1221,6 +1240,7 @@ def add_vllm_package_data(filename: str) -> None: "av", "scipy", "soundfile", + "soxr", "mistral_common[audio]", ], # Required for audio processing "video": [], # Kept for backwards compatibility @@ -1239,6 +1259,8 @@ def add_vllm_package_data(filename: str) -> None: "opentelemetry-exporter-otlp>=1.26.0", "opentelemetry-semantic-conventions-ai>=0.4.1", ], + # extra quantization plugin + "extra-quant": ["vllm-gguf-plugin>=0.0.2"], }, cmdclass=cmdclass, package_data=package_data, diff --git a/tests/compile/conftest.py b/tests/compile/conftest.py index 1263cce04c6c..7d15b5c47e55 100644 --- a/tests/compile/conftest.py +++ b/tests/compile/conftest.py @@ -24,6 +24,7 @@ def test_something(mock_cuda_platform): def _mock_platform(is_cuda: bool = True, capability: tuple[int, int] | None = None): mock_platform = MagicMock() mock_platform.is_cuda.return_value = is_cuda + mock_platform.is_xpu.return_value = False device_capability = ( DeviceCapability(*capability) if capability is not None else None ) @@ -46,3 +47,25 @@ def is_device_capability_family( yield mock_platform return _mock_platform + + +@pytest.fixture +def mock_xpu_platform(): + """ + Fixture that returns a factory for creating mocked XPU platforms. + + Usage: + def test_something(mock_xpu_platform): + with mock_xpu_platform(): + # test code + """ + + @contextmanager + def _mock_platform(): + mock_platform = MagicMock() + mock_platform.is_cuda.return_value = False + mock_platform.is_xpu.return_value = True + with patch("vllm.platforms.current_platform", mock_platform): + yield mock_platform + + return _mock_platform diff --git a/tests/compile/fullgraph/test_full_graph.py b/tests/compile/fullgraph/test_full_graph.py index ed4c92d90ff7..cc138454802b 100644 --- a/tests/compile/fullgraph/test_full_graph.py +++ b/tests/compile/fullgraph/test_full_graph.py @@ -39,12 +39,6 @@ def models_list(*, all: bool = True, keywords: list[str] | None = None): ] ) - # TODO: figure out why this fails. - if False and is_quant_method_supported("gguf"): # noqa: SIM223 - TEST_MODELS.append( - ("TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF", {"quantization": "gguf"}) - ) - if is_quant_method_supported("gptq"): TEST_MODELS.append( ("TheBloke/TinyLlama-1.1B-Chat-v0.3-GPTQ", {"quantization": "gptq"}) diff --git a/tests/compile/test_sequence_parallelism_threshold.py b/tests/compile/test_sequence_parallelism_threshold.py index 42e374cd95d7..090b77b330ab 100644 --- a/tests/compile/test_sequence_parallelism_threshold.py +++ b/tests/compile/test_sequence_parallelism_threshold.py @@ -108,3 +108,85 @@ def test_hidden_size_boundary(self, mock_cuda_platform): element_size=2, ) assert result is not None + + +# XPU-specific constants (must match sequence_parallelism.py values) +_XPU_MIN_HIDDEN_SIZE = 4096 +_XPU_MIN_PER_GPU_SIZE_MB = 8.0 + + +class TestGetSequenceParallelismThresholdXPU: + """Tests for get_sequence_parallelism_threshold on XPU platform.""" + + def test_xpu_small_hidden_size_returns_none(self, mock_xpu_platform): + """XPU with hidden_size below threshold should return None.""" + with mock_xpu_platform(): + result = get_sequence_parallelism_threshold( + hidden_size=_XPU_MIN_HIDDEN_SIZE - 1, + tp_size=2, + element_size=2, + ) + assert result is None + + def test_xpu_large_model_returns_threshold(self, mock_xpu_platform): + """XPU with hidden_size >= threshold should return calculated value.""" + with mock_xpu_platform(): + hidden_size = _XPU_MIN_HIDDEN_SIZE + tp_size = 2 + element_size = 2 + result = get_sequence_parallelism_threshold( + hidden_size=hidden_size, + tp_size=tp_size, + element_size=element_size, + ) + # (8 * 2 * 1024 * 1024) // (4096 * 2) = 2048 + MiB = 1024 * 1024 + expected = int( + (_XPU_MIN_PER_GPU_SIZE_MB * tp_size * MiB) // (hidden_size * element_size) + ) + assert result == expected + assert result == 2048 + + @pytest.mark.parametrize( + "hidden_size,tp_size,element_size,expected", + [ + # (8 * 1 * 1024 * 1024) // (4096 * 2) = 1024 + (4096, 1, 2, 1024), + # (8 * 4 * 1024 * 1024) // (4096 * 2) = 4096 + (4096, 4, 2, 4096), + # (8 * 2 * 1024 * 1024) // (8192 * 2) = 1024 + (8192, 2, 2, 1024), + # (8 * 2 * 1024 * 1024) // (4096 * 4) = 1024 + (4096, 2, 4, 1024), + ], + ) + def test_xpu_threshold_calculation_variations( + self, mock_xpu_platform, hidden_size, tp_size, element_size, expected + ): + """Test XPU threshold calculation with various parameter combinations.""" + with mock_xpu_platform(): + result = get_sequence_parallelism_threshold( + hidden_size=hidden_size, + tp_size=tp_size, + element_size=element_size, + ) + assert result == expected + + def test_xpu_hidden_size_boundary(self, mock_xpu_platform): + """Test behavior at the exact XPU hidden_size boundary.""" + with mock_xpu_platform(): + # Just below threshold + result = get_sequence_parallelism_threshold( + hidden_size=_XPU_MIN_HIDDEN_SIZE - 1, + tp_size=2, + element_size=2, + ) + assert result is None + + # Exactly at threshold + result = get_sequence_parallelism_threshold( + hidden_size=_XPU_MIN_HIDDEN_SIZE, + tp_size=2, + element_size=2, + ) + assert result is not None diff --git a/tests/conftest.py b/tests/conftest.py index 5db457e29395..4fc43ef04b10 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -51,6 +51,7 @@ from vllm.assets.audio import AudioAsset from vllm.assets.image import ImageAsset from vllm.assets.video import VideoAsset +from vllm.config.cache import CacheConfig from vllm.config.model import ConvertOption, RunnerOption, _get_and_verify_dtype from vllm.connections import global_http_connection from vllm.distributed import ( @@ -924,6 +925,20 @@ def __init__( num_speculative_tokens + 1 ) + from vllm.platforms import current_platform + + if current_platform.is_rocm(): + gpu_memory_utilization = kwargs.get( + "gpu_memory_utilization", + CacheConfig.gpu_memory_utilization, + ) + # V1 startup requires free_memory >= total * gpu_memory_utilization. + # ROCm CI can hand a test a device that is still lazily releasing + # VRAM from a previous process, so wait before constructing LLM. + from tests.utils import wait_for_rocm_memory_to_settle + + wait_for_rocm_memory_to_settle(threshold_ratio=1.0 - gpu_memory_utilization) + with init_ctx: self.llm = LLM( model=model_name, @@ -1279,6 +1294,7 @@ def __exit__(self, exc_type, exc_value, traceback): # Ignore shutdown errors as cleanup will still proceed pass del self.llm + torch._dynamo.reset() cleanup_dist_env_and_memory() self._wait_for_rocm_memory_release(gpu_memory_utilization) diff --git a/tests/distributed/test_pipeline_parallel.py b/tests/distributed/test_pipeline_parallel.py index 853074032006..d1196b8e0d50 100644 --- a/tests/distributed/test_pipeline_parallel.py +++ b/tests/distributed/test_pipeline_parallel.py @@ -155,9 +155,6 @@ def iter_params(self, model_id: str): "stabilityai/stablelm-3b-4e1t": PPTestSettings.fast(), "bigcode/starcoder2-3b": PPTestSettings.fast(), "upstage/solar-pro-preview-instruct": PPTestSettings.fast(load_format="dummy"), - # FIXME: Cannot load tokenizer in latest transformers version. - # Need to use tokenizer from `meta-llama/Llama-2-7b-chat-hf` - # "xverse/XVERSE-7B-Chat": PPTestSettings.fast(), # [Encoder-only] # TODO: Implement PP # "facebook/bart-base": PPTestSettings.fast(), diff --git a/tests/engine/test_arg_utils.py b/tests/engine/test_arg_utils.py index 9b21f3eebc10..9d34975032e1 100644 --- a/tests/engine/test_arg_utils.py +++ b/tests/engine/test_arg_utils.py @@ -206,6 +206,14 @@ def test_get_kwargs(): assert kwargs["nested_config"]["type"]('{"field": 2}') == NestedConfig(2) # type: ignore[call-arg] +def test_jit_monitor_verbose_arg(): + parser = EngineArgs.add_cli_args(FlexibleArgumentParser()) + args = parser.parse_args(["--jit-monitor-verbose"]) + + assert args.jit_monitor_verbose + assert EngineArgs(model="test", jit_monitor_verbose=True).jit_monitor_verbose + + def test_hf_token_get_kwargs(): kwargs = get_kwargs(ModelConfig)["hf_token"] diff --git a/tests/entrypoints/anthropic/test_anthropic_messages_conversion.py b/tests/entrypoints/anthropic/test_anthropic_messages_conversion.py index 21d5154c6756..3edc09801e8a 100644 --- a/tests/entrypoints/anthropic/test_anthropic_messages_conversion.py +++ b/tests/entrypoints/anthropic/test_anthropic_messages_conversion.py @@ -996,3 +996,39 @@ async def sse_input(): assert "text" in block_starts assert events[-1][0] == "message_stop" + + +class TestMessageStartIncludesTypeAndRole: + """Regression test for issue #45367: the streaming message_start event is + serialized with exclude_unset=True, which silently dropped the + default-valued ``type``/``role`` fields of the nested message object. + Strict Anthropic SDK clients (e.g. Claude Code) validate + ``message_start.message.type``/``role`` and reject the whole stream when + they are missing. + """ + + @pytest.mark.asyncio + async def test_message_start_contains_message_type_and_role(self): + async def sse_input(): + yield _make_stream_chunk( + delta=DeltaMessage(content="Hello"), + usage=UsageInfo( + prompt_tokens=20, + total_tokens=20, + completion_tokens=0, + ), + ) + yield _make_stream_chunk(finish_reason="stop") + yield "data: [DONE]" + + converter = _make_stream_converter() + output = [] + async for event in converter.message_stream_converter(sse_input()): + output.append(event) + + events = _parse_sse_events(output) + + assert events[0][0] == "message_start" + message = events[0][1]["message"] + assert message["type"] == "message" + assert message["role"] == "assistant" diff --git a/tests/entrypoints/anthropic/test_protocol_exports.py b/tests/entrypoints/anthropic/test_protocol_exports.py new file mode 100644 index 000000000000..466f40e3ccf5 --- /dev/null +++ b/tests/entrypoints/anthropic/test_protocol_exports.py @@ -0,0 +1,50 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Regression tests for Anthropic protocol exports used by serving. + +Guards against Docker/nightly images shipping a stale protocol module that is +missing symbols imported by ``vllm.entrypoints.anthropic.serving`` (issue #44759). +""" + +import pytest + +from vllm.entrypoints.anthropic.protocol import ( + AnthropicContentBlock, + AnthropicContextManagement, + AnthropicCountTokensRequest, + AnthropicCountTokensResponse, + AnthropicDelta, + AnthropicError, + AnthropicMessagesRequest, + AnthropicMessagesResponse, + AnthropicOutputConfig, + AnthropicStreamEvent, + AnthropicUsage, +) + +pytestmark = pytest.mark.skip_global_cleanup + +SERVING_PROTOCOL_EXPORTS = ( + AnthropicContentBlock, + AnthropicContextManagement, + AnthropicCountTokensRequest, + AnthropicCountTokensResponse, + AnthropicDelta, + AnthropicError, + AnthropicMessagesRequest, + AnthropicMessagesResponse, + AnthropicOutputConfig, + AnthropicStreamEvent, + AnthropicUsage, +) + + +def test_serving_protocol_exports_are_importable(): + for export in SERVING_PROTOCOL_EXPORTS: + assert export is not None + + +def test_anthropic_output_config_instantiation(): + config = AnthropicOutputConfig() + assert config.effort is None + assert config.format is None diff --git a/tests/entrypoints/openai/chat_completion/test_completion_with_function_calling.py b/tests/entrypoints/openai/chat_completion/test_completion_with_function_calling.py index 839793fde856..a3e05027b38e 100644 --- a/tests/entrypoints/openai/chat_completion/test_completion_with_function_calling.py +++ b/tests/entrypoints/openai/chat_completion/test_completion_with_function_calling.py @@ -250,6 +250,7 @@ async def k2_client(k2_server): @pytest.mark.asyncio +@pytest.mark.skip(reason="Skipping Kimi K2 tool ID test") @pytest.mark.parametrize("model_name", [MODEL_NAME]) @pytest.mark.parametrize("stream", [True, False]) @pytest.mark.parametrize("tool_choice", ["required"]) @@ -442,7 +443,7 @@ async def test_named_tool_use( if delta.role: assert delta.role == "assistant" assert delta.content is None or len(delta.content) == 0 - if delta.tool_calls: + if delta.tool_calls and delta.tool_calls[0].function.arguments: output.append(delta.tool_calls[0].function.arguments) if chunk.choices[0].finish_reason is not None: finish_reason_count += 1 diff --git a/tests/entrypoints/openai/chat_completion/test_serving_chat.py b/tests/entrypoints/openai/chat_completion/test_serving_chat.py index e523cc2d4a36..a12662ec7fc2 100644 --- a/tests/entrypoints/openai/chat_completion/test_serving_chat.py +++ b/tests/entrypoints/openai/chat_completion/test_serving_chat.py @@ -23,7 +23,11 @@ ChatCompletionRequest, ChatCompletionResponse, ) -from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat +from vllm.entrypoints.openai.chat_completion.serving import ( + OpenAIServingChat, + _get_mm_token_counts, + _make_prompt_tokens_details, +) from vllm.entrypoints.openai.engine.protocol import ( ErrorResponse, RequestResponseMetadata, @@ -37,6 +41,7 @@ from vllm.entrypoints.serve.render.serving import OpenAIServingRender from vllm.exceptions import VLLMValidationError from vllm.inputs import TokensPrompt +from vllm.multimodal.inputs import PlaceholderRange from vllm.outputs import CompletionOutput, RequestOutput from vllm.parser import HarmonyParser from vllm.renderers.hf import HfRenderer @@ -635,6 +640,37 @@ def test_async_serving_chat_init(): assert serving_completion.chat_template == CHAT_TEMPLATE +def test_mm_prompt_tokens_details(): + # Text-only input has no multimodal placeholders. + assert _get_mm_token_counts({"type": "tokens"}) == {} + + # Per-modality counts sum each modality's placeholder ranges. + counts = _get_mm_token_counts( + { + "mm_placeholders": { + "image": [ + PlaceholderRange(offset=0, length=576), + PlaceholderRange(offset=600, length=24), + ], + "video": [PlaceholderRange(offset=700, length=1200)], + } + } + ) + assert counts == {"image": 600, "video": 1200} + + # Gated off, or nothing to report -> no details. + assert _make_prompt_tokens_details(False, 5, counts) is None + assert _make_prompt_tokens_details(True, None, None) is None + + # Zero cached_tokens is still reported (not None), matching the cached-only + # behavior; multimodal counts ride alongside even when cached_tokens is None. + assert _make_prompt_tokens_details(True, 0, None).cached_tokens == 0 + details = _make_prompt_tokens_details(True, None, counts) + assert details.cached_tokens is None + assert details.multimodal_tokens == {"image": 600, "video": 1200} + assert _make_prompt_tokens_details(True, 3, counts).cached_tokens == 3 + + @pytest.mark.asyncio async def test_serving_chat_returns_correct_model_name(): mock_engine = MagicMock(spec=AsyncLLM) @@ -1314,6 +1350,21 @@ async def result_generator(): else serving_chat.chat_completion_full_generator ) + chat_template_kwargs = serving_chat._effective_chat_template_kwargs(req) + if stream: + extra_kwargs: dict[str, Any] = { + "chat_template_kwargs": chat_template_kwargs, + } + else: + parser = None + if serving_chat.parser_cls is not None: + parser = serving_chat.parser_cls( + tokenizer, + req.tools, + chat_template_kwargs=chat_template_kwargs, + ) + extra_kwargs = {"parser": parser} + result = generator_func( request=req, result_generator=result_generator(), @@ -1325,7 +1376,7 @@ async def result_generator(): request_id=req.request_id, model_name=req.model, ), - chat_template_kwargs=serving_chat._effective_chat_template_kwargs(req), + **extra_kwargs, ) if stream: diff --git a/tests/entrypoints/openai/test_responses_parser_unified.py b/tests/entrypoints/openai/responses/test_parsable_context_unit.py similarity index 66% rename from tests/entrypoints/openai/test_responses_parser_unified.py rename to tests/entrypoints/openai/responses/test_parsable_context_unit.py index 231ccf34fc2a..0aadfbe99d35 100644 --- a/tests/entrypoints/openai/test_responses_parser_unified.py +++ b/tests/entrypoints/openai/responses/test_parsable_context_unit.py @@ -1,10 +1,9 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Unit tests for ResponsesParser with the unified Parser interface. +"""Unit tests for ParsableContext's parsing behavior. -These tests verify that ResponsesParser correctly delegates to the unified -Parser (via parse) instead of calling separate ReasoningParser / ToolParser -instances directly. +These tests verify that ParsableContext correctly delegates to the unified +Parser (via parse) and properly builds response output items. """ from collections.abc import Sequence @@ -18,12 +17,9 @@ FunctionCall, ToolCall, ) -from vllm.entrypoints.openai.parser.responses_parser import ( - ResponsesParser, - get_responses_parser_for_simple_context, -) +from vllm.entrypoints.openai.responses.context import ParsableContext from vllm.entrypoints.openai.responses.protocol import ResponsesRequest -from vllm.outputs import CompletionOutput +from vllm.outputs import CompletionOutput, RequestOutput from vllm.parser.abstract_parser import DelegatingParser pytestmark = pytest.mark.skip_global_cleanup @@ -162,32 +158,42 @@ def _make_request(**overrides) -> ResponsesRequest: return ResponsesRequest.model_validate(defaults) -def _make_output( +def _make_request_output( text: str = "Hello, world!", token_ids: Sequence[int] = (1, 2, 3), finish_reason: str = "stop", -) -> CompletionOutput: - return CompletionOutput( - index=0, - text=text, - token_ids=list(token_ids), - cumulative_logprob=None, - logprobs=None, - finish_reason=finish_reason, +) -> RequestOutput: + return RequestOutput( + request_id="test", + prompt=None, + prompt_token_ids=[], + prompt_logprobs=None, + outputs=[ + CompletionOutput( + index=0, + text=text, + token_ids=list(token_ids), + cumulative_logprob=None, + logprobs=None, + finish_reason=finish_reason, + ) + ], + finished=True, ) -def _make_parser(parser_cls, **overrides): +def _make_context(parser_cls, **overrides): defaults = dict( tokenizer=MagicMock(), parser_cls=parser_cls, response_messages=[], request=_make_request(), + available_tools=None, chat_template=None, chat_template_content_format="auto", ) defaults.update(overrides) - return ResponsesParser(**defaults) + return ParsableContext(**defaults) # --------------------------------------------------------------------------- @@ -197,22 +203,22 @@ def _make_parser(parser_cls, **overrides): def test_process_text_with_parser(): """Parser with no reasoning/tools returns a single message item.""" - parser = _make_parser(_NoOpParser) - parser.process(_make_output(text="Hello!")) + ctx = _make_context(_NoOpParser) + ctx.append_output(_make_request_output(text="Hello!")) - assert len(parser.response_messages) == 1 - msg = parser.response_messages[0] + assert len(ctx.response_messages) == 1 + msg = ctx.response_messages[0] assert msg.type == "message" assert msg.content[0].text == "Hello!" def test_process_text_without_parser(): """parser_cls=None falls back to plain text wrapping.""" - parser = _make_parser(None) - parser.process(_make_output(text="Hello!")) + ctx = _make_context(None) + ctx.append_output(_make_request_output(text="Hello!")) - assert len(parser.response_messages) == 1 - msg = parser.response_messages[0] + assert len(ctx.response_messages) == 1 + msg = ctx.response_messages[0] assert msg.type == "message" assert msg.content[0].text == "Hello!" @@ -224,18 +230,18 @@ def test_process_text_without_parser(): def test_process_empty_text_without_parser(): """Empty text with no parser produces no output items.""" - parser = _make_parser(None) - parser.process(_make_output(text="")) + ctx = _make_context(None) + ctx.append_output(_make_request_output(text="")) - assert len(parser.response_messages) == 0 + assert len(ctx.response_messages) == 0 def test_process_empty_text_with_parser(): """Empty text with parser produces no output items.""" - parser = _make_parser(_NoOpParser) - parser.process(_make_output(text="")) + ctx = _make_context(_NoOpParser) + ctx.append_output(_make_request_output(text="")) - assert len(parser.response_messages) == 0 + assert len(ctx.response_messages) == 0 # --------------------------------------------------------------------------- @@ -245,26 +251,28 @@ def test_process_empty_text_with_parser(): def test_process_extracts_reasoning(): """Parser that finds reasoning produces both reasoning and message items.""" - parser = _make_parser(_ReasoningOnlyParser) - parser.process(_make_output(text="Let me checkThe answer is 42")) + ctx = _make_context(_ReasoningOnlyParser) + ctx.append_output( + _make_request_output(text="Let me checkThe answer is 42") + ) - types = [m.type for m in parser.response_messages] + types = [m.type for m in ctx.response_messages] assert "reasoning" in types assert "message" in types - reasoning_item = next(m for m in parser.response_messages if m.type == "reasoning") + reasoning_item = next(m for m in ctx.response_messages if m.type == "reasoning") assert reasoning_item.content[0].text == "Let me check" - message_item = next(m for m in parser.response_messages if m.type == "message") + message_item = next(m for m in ctx.response_messages if m.type == "message") assert message_item.content[0].text == "The answer is 42" def test_process_reasoning_only_no_content(): """When reasoning consumes all text, only a reasoning item is produced.""" - parser = _make_parser(_ReasoningOnlyParser) - parser.process(_make_output(text="Just thinking")) + ctx = _make_context(_ReasoningOnlyParser) + ctx.append_output(_make_request_output(text="Just thinking")) - types = [m.type for m in parser.response_messages] + types = [m.type for m in ctx.response_messages] assert "reasoning" in types assert "message" not in types @@ -286,13 +294,13 @@ def test_process_extracts_tool_calls(): } ], ) - parser = _make_parser(_ToolCallingParser, request=request, enable_auto_tools=True) - parser.process(_make_output(text="calling tool")) + ctx = _make_context(_ToolCallingParser, request=request, enable_auto_tools=True) + ctx.append_output(_make_request_output(text="calling tool")) - types = [m.type for m in parser.response_messages] + types = [m.type for m in ctx.response_messages] assert "function_call" in types - tool_item = next(m for m in parser.response_messages if m.type == "function_call") + tool_item = next(m for m in ctx.response_messages if m.type == "function_call") assert tool_item.name == "get_weather" assert tool_item.arguments == '{"location": "Paris"}' assert tool_item.status == "completed" @@ -304,15 +312,15 @@ def test_process_extracts_tool_calls(): def test_finish_reason_tracked(): - """finish_reason from CompletionOutput is stored on the parser.""" - parser = _make_parser(_NoOpParser) - assert parser.finish_reason is None + """finish_reason from CompletionOutput is stored on the context.""" + ctx = _make_context(_NoOpParser) + assert ctx.finish_reason is None - parser.process(_make_output(finish_reason="stop")) - assert parser.finish_reason == "stop" + ctx.append_output(_make_request_output(finish_reason="stop")) + assert ctx.finish_reason == "stop" - parser.process(_make_output(finish_reason="length")) - assert parser.finish_reason == "length" + ctx.append_output(_make_request_output(finish_reason="length")) + assert ctx.finish_reason == "length" # --------------------------------------------------------------------------- @@ -321,62 +329,27 @@ def test_finish_reason_tracked(): def test_multi_turn_accumulation(): - """Multiple process() calls accumulate response_messages.""" - parser = _make_parser(_NoOpParser) + """Multiple append_output() calls accumulate response_messages.""" + ctx = _make_context(_NoOpParser) - parser.process(_make_output(text="First turn")) - parser.process(_make_output(text="Second turn")) + ctx.append_output(_make_request_output(text="First turn")) + ctx.append_output(_make_request_output(text="Second turn")) - assert len(parser.response_messages) == 2 - texts = [m.content[0].text for m in parser.response_messages] + assert len(ctx.response_messages) == 2 + texts = [m.content[0].text for m in ctx.response_messages] assert texts == ["First turn", "Second turn"] def test_num_init_messages_offset(): """Initial messages are preserved and offset works correctly.""" init_messages = [MagicMock(type="message")] - parser = _make_parser(_NoOpParser, response_messages=init_messages) + ctx = _make_context(_NoOpParser, response_messages=init_messages) - assert parser.num_init_messages == 1 + assert ctx.num_init_messages == 1 - parser.process(_make_output(text="New output")) + ctx.append_output(_make_request_output(text="New output")) - assert len(parser.response_messages) == 2 - items = parser.make_response_output_items_from_parsable_context() + assert len(ctx.response_messages) == 2 + items = ctx.make_response_output_items() assert len(items) == 1 assert items[0].type == "message" - - -# --------------------------------------------------------------------------- -# Tests: factory function -# --------------------------------------------------------------------------- - - -def test_factory_function_creates_parser(): - """get_responses_parser_for_simple_context returns a working parser.""" - rp = get_responses_parser_for_simple_context( - tokenizer=MagicMock(), - parser_cls=_NoOpParser, - response_messages=[], - request=_make_request(), - chat_template=None, - chat_template_content_format="auto", - ) - assert isinstance(rp, ResponsesParser) - - rp.process(_make_output(text="Works!")) - assert len(rp.response_messages) == 1 - - -def test_factory_function_none_parser(): - """Factory function works with parser_cls=None.""" - rp = get_responses_parser_for_simple_context( - tokenizer=MagicMock(), - parser_cls=None, - response_messages=[], - request=_make_request(), - chat_template=None, - chat_template_content_format="auto", - ) - assert isinstance(rp, ResponsesParser) - assert rp.parser_instance is None diff --git a/tests/entrypoints/pooling/embed/test_io_processor.py b/tests/entrypoints/pooling/embed/test_io_processor.py index 341ccbd5f0c5..8f8f8faa8adf 100644 --- a/tests/entrypoints/pooling/embed/test_io_processor.py +++ b/tests/entrypoints/pooling/embed/test_io_processor.py @@ -3,6 +3,7 @@ """Unit tests for EmbedIOProcessor.""" import pytest +from pydantic import TypeAdapter, ValidationError from vllm import PoolingParams from vllm.entrypoints.pooling.embed.io_processor import EmbedIOProcessor @@ -10,10 +11,195 @@ CohereEmbedContent, CohereEmbedInput, CohereEmbedRequest, + EmbeddingBatchChatInputRequest, + EmbeddingBatchChatRequest, + EmbeddingChatInputRequest, + EmbeddingChatRequest, + EmbeddingCompletionRequest, + EmbeddingRequest, ) from vllm.entrypoints.pooling.typing import PoolingServeContext +class TestEmbeddingRequestParsing: + """Unit tests for OpenAI embedding request parsing.""" + + def test_input_messages_parses_as_chat_request(self): + request = TypeAdapter(EmbeddingRequest).validate_python( + { + "model": "test", + "input": [{"role": "user", "content": "hello"}], + "chat_template_kwargs": {"instruction": "Represent the query: "}, + } + ) + + assert isinstance(request, EmbeddingChatInputRequest) + assert request.input == [{"role": "user", "content": "hello"}] + assert request.messages == [{"role": "user", "content": "hello"}] + assert request.chat_template_kwargs == {"instruction": "Represent the query: "} + + def test_batched_input_messages_parses_as_batch_chat_input_request(self): + request = TypeAdapter(EmbeddingRequest).validate_python( + { + "model": "test", + "input": [ + [{"role": "user", "content": "hello"}], + [{"role": "user", "content": "goodbye"}], + ], + "chat_template_kwargs": {"instruction": "Represent the query: "}, + } + ) + + assert isinstance(request, EmbeddingBatchChatInputRequest) + assert request.input == [ + [{"role": "user", "content": "hello"}], + [{"role": "user", "content": "goodbye"}], + ] + assert request.messages == [ + [{"role": "user", "content": "hello"}], + [{"role": "user", "content": "goodbye"}], + ] + assert request.chat_template_kwargs == {"instruction": "Represent the query: "} + + def test_token_ids_still_parse_as_completion_request(self): + request = TypeAdapter(EmbeddingRequest).validate_python( + { + "model": "test", + "input": [[1, 2, 3], [4, 5]], + } + ) + + assert isinstance(request, EmbeddingCompletionRequest) + assert request.input == [[1, 2, 3], [4, 5]] + + def test_messages_still_parses_as_chat_request(self): + request = TypeAdapter(EmbeddingRequest).validate_python( + { + "model": "test", + "messages": [{"role": "user", "content": "hello"}], + "chat_template_kwargs": {"instruction": "Represent the query: "}, + } + ) + + assert isinstance(request, EmbeddingChatRequest) + assert request.messages == [{"role": "user", "content": "hello"}] + assert request.chat_template_kwargs == {"instruction": "Represent the query: "} + + def test_batched_messages_parses_as_batch_chat_request(self): + request = TypeAdapter(EmbeddingRequest).validate_python( + { + "model": "test", + "messages": [ + [{"role": "user", "content": "hello"}], + [{"role": "user", "content": "goodbye"}], + ], + "chat_template_kwargs": {"instruction": "Represent the query: "}, + } + ) + + assert isinstance(request, EmbeddingBatchChatRequest) + assert request.messages == [ + [{"role": "user", "content": "hello"}], + [{"role": "user", "content": "goodbye"}], + ] + assert request.chat_template_kwargs == {"instruction": "Represent the query: "} + + +class TestCohereEmbedRequestParsing: + """Unit tests for Cohere embed request parsing.""" + + @pytest.mark.parametrize( + "request_body", + [ + {"model": "test"}, + {"model": "test", "texts": ["hello"], "images": ["image-uri"]}, + { + "model": "test", + "texts": ["hello"], + "inputs": [ + {"content": [{"type": "text", "text": "hello"}]}, + ], + }, + { + "model": "test", + "images": ["image-uri"], + "inputs": [ + {"content": [{"type": "text", "text": "hello"}]}, + ], + }, + {"model": "test", "texts": []}, + {"model": "test", "images": []}, + {"model": "test", "inputs": []}, + ], + ) + def test_rejects_invalid_input_field_combinations(self, request_body): + with pytest.raises( + ValidationError, + match="Exactly one of texts, images, or inputs must be provided", + ): + CohereEmbedRequest(**request_body) + + @pytest.mark.parametrize( + "request_body", + [ + {"model": "test", "texts": ["hello"]}, + {"model": "test", "images": ["image-uri"]}, + { + "model": "test", + "inputs": [ + {"content": [{"type": "text", "text": "hello"}]}, + ], + }, + { + "model": "test", + "inputs": [ + { + "content": [ + {"type": "image_url", "image_url": {"url": "image-uri"}} + ] + }, + ], + }, + ], + ) + def test_accepts_exactly_one_non_empty_input_field(self, request_body): + request = CohereEmbedRequest(**request_body) + + assert request.model == "test" + + @pytest.mark.parametrize( + ("content", "error"), + [ + ( + {"type": "text"}, + "CohereEmbedContent with type='text' requires text", + ), + ( + {"type": "image_url"}, + "CohereEmbedContent with type='image_url' requires image_url.url", + ), + ( + {"type": "image_url", "image_url": {}}, + "CohereEmbedContent with type='image_url' requires image_url.url", + ), + ( + {"type": "image_url", "image_url": {"url": ""}}, + "CohereEmbedContent with type='image_url' requires image_url.url", + ), + ], + ) + def test_rejects_invalid_mixed_content_payloads(self, content, error): + with pytest.raises(ValidationError, match=error): + CohereEmbedRequest( + model="test", + inputs=[ + { + "content": [content], + }, + ], + ) + + class TestResolveTruncation: """Unit tests for EmbedIOProcessor._resolve_cohere_truncation.""" @@ -324,3 +510,113 @@ def batch_render_chat( }, ) ] + + +class TestPreProcessOpenAIEmbeddingChatOnline: + """Unit tests for OpenAI embedding chat preprocessing.""" + + class _FakeModelConfig: + max_model_len = 128 + encoder_config: dict[str, object] = {} + pooler_config = None + multimodal_config = None + is_encoder_decoder = False + + class _FakeRenderer: + tokenizer = object() + + def __init__(self): + self.calls = [] + + def render_chat( + self, + all_messages, + chat_params, + tok_params, + prompt_extras=None, + ): + self.calls.append( + { + "all_messages": all_messages, + "chat_params": chat_params, + "tok_params": tok_params, + "prompt_extras": prompt_extras, + } + ) + return all_messages, [ + {"prompt_token_ids": [index]} for index, _ in enumerate(all_messages) + ] + + @classmethod + def _make_handler(cls, renderer): + handler = object.__new__(EmbedIOProcessor) + handler.renderer = renderer + handler.model_config = cls._FakeModelConfig() + handler.chat_template = "template" + handler.chat_template_content_format = "auto" + handler.trust_request_chat_template = False + handler.enable_chunked_processing = False + return handler + + @staticmethod + def _make_context( + request: ( + EmbeddingChatRequest + | EmbeddingBatchChatRequest + | EmbeddingChatInputRequest + | EmbeddingBatchChatInputRequest + ), + ) -> PoolingServeContext[ + EmbeddingChatRequest + | EmbeddingBatchChatRequest + | EmbeddingChatInputRequest + | EmbeddingBatchChatInputRequest + ]: + return PoolingServeContext( + request=request, + pooling_params=PoolingParams(), + model_name="test", + request_id="embd-test", + ) + + def test_chat_template_kwargs_forwarded_for_batched_input_messages(self): + request = TypeAdapter(EmbeddingRequest).validate_python( + { + "model": "test", + "input": [ + [{"role": "user", "content": "hello"}], + [{"role": "user", "content": "goodbye"}], + ], + "add_generation_prompt": True, + "chat_template_kwargs": {"instruction": "Represent the query: "}, + "mm_processor_kwargs": {"max_pixels": 1}, + "cache_salt": "salt", + } + ) + assert isinstance(request, EmbeddingBatchChatInputRequest) + + renderer = self._FakeRenderer() + handler = self._make_handler(renderer) + ctx = self._make_context(request) + + handler.pre_process_online(ctx) + + assert ctx.engine_inputs == [ + {"prompt_token_ids": [0]}, + {"prompt_token_ids": [1]}, + ] + assert len(renderer.calls) == 1 + + call = renderer.calls[0] + assert call["all_messages"] == request.messages + assert call["prompt_extras"] == { + "mm_processor_kwargs": {"max_pixels": 1}, + "cache_salt": "salt", + } + + chat_template_kwargs = call["chat_params"].chat_template_kwargs + assert chat_template_kwargs["instruction"] == "Represent the query: " + assert chat_template_kwargs["add_generation_prompt"] is True + assert chat_template_kwargs["continue_final_message"] is False + assert "tools" not in chat_template_kwargs + assert chat_template_kwargs["tokenize"] is False diff --git a/tests/entrypoints/serve/instrumentator/test_metrics.py b/tests/entrypoints/serve/instrumentator/test_metrics.py index 9095f80e20f2..8e6fdb704524 100644 --- a/tests/entrypoints/serve/instrumentator/test_metrics.py +++ b/tests/entrypoints/serve/instrumentator/test_metrics.py @@ -289,6 +289,17 @@ async def test_metrics_exist( continue assert metric in response.text + cache_config_samples = [ + sample + for family in text_string_to_metric_families(response.text) + if family.name == "vllm:cache_config_info" + for sample in family.samples + ] + assert cache_config_samples + for sample in cache_config_samples: + assert sample.labels.get("kv_cache_size_tokens") not in (None, "None", "") + assert sample.labels.get("kv_cache_max_concurrency") not in (None, "None", "") + @pytest.mark.asyncio async def test_abort_metrics_reset( diff --git a/tests/entrypoints/serve/render/test_derender.py b/tests/entrypoints/serve/render/test_derender.py new file mode 100644 index 000000000000..a3006595c19a --- /dev/null +++ b/tests/entrypoints/serve/render/test_derender.py @@ -0,0 +1,488 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +"""Tests for the /derender endpoints (postprocessing counterpart to /render).""" + +import httpx +import pytest +import pytest_asyncio + +from tests.utils import RemoteLaunchRenderServer + +MODEL_NAME = "hmellor/tiny-random-LlamaForCausalLM" + + +@pytest.fixture(scope="module") +def server(): + with RemoteLaunchRenderServer(MODEL_NAME, []) as remote_server: + yield remote_server + + +@pytest_asyncio.fixture +async def client(server): + async with httpx.AsyncClient( + base_url=server.url_for(""), timeout=30.0 + ) as http_client: + yield http_client + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +async def _render_chat(client: httpx.AsyncClient) -> dict: + """Render a minimal chat request and return the GenerateRequest dict.""" + resp = await client.post( + "/v1/chat/completions/render", + json={ + "model": MODEL_NAME, + "messages": [{"role": "user", "content": "Hello"}], + }, + ) + assert resp.status_code == 200 + return resp.json() + + +def _make_generate_response( + token_ids: list[int] | None, + request_id: str = "chatcmpl-test-id", + finish_reason: str = "stop", + logprobs: dict | None = None, + prompt_logprobs: list | None = None, + kv_transfer_params: dict | None = None, +) -> dict: + choice: dict = { + "index": 0, + "token_ids": token_ids, + "finish_reason": finish_reason, + "logprobs": logprobs, + } + return { + "request_id": request_id, + "choices": [choice], + "prompt_logprobs": prompt_logprobs, + "kv_transfer_params": kv_transfer_params, + } + + +def _make_logprobs_with_placeholders(token_id: int = 1234) -> dict: + entry = { + "token": f"token_id:{token_id}", + "logprob": -1.0, + "bytes": None, + "top_logprobs": [ + {"token": f"token_id:{token_id + 1}", "logprob": -2.0, "bytes": None} + ], + } + return {"content": [entry]} + + +# --------------------------------------------------------------------------- +# Chat derender tests +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_derender_chat_roundtrip(client): + """Render then derender: decoded content should be a non-empty string.""" + gen_req = await _render_chat(client) + # Use the first 5 rendered token IDs as synthetic "generated" tokens. + synthetic_ids = gen_req["token_ids"][:5] + + response = await client.post( + "/v1/chat/completions/derender", + json={ + "model": MODEL_NAME, + "generate_response": _make_generate_response(synthetic_ids), + }, + ) + assert response.status_code == 200 + data = response.json() + assert data["object"] == "chat.completion" + assert len(data["choices"]) == 1 + assert data["choices"][0]["message"]["content"] + assert data["choices"][0]["message"]["role"] == "assistant" + + +@pytest.mark.asyncio +async def test_derender_chat_usage(client): + """Supplied prompt_tokens flows through into usage correctly.""" + gen_req = await _render_chat(client) + synthetic_ids = gen_req["token_ids"][:3] + + response = await client.post( + "/v1/chat/completions/derender", + json={ + "model": MODEL_NAME, + "generate_response": _make_generate_response(synthetic_ids), + "prompt_tokens": 10, + }, + ) + assert response.status_code == 200 + usage = response.json()["usage"] + assert usage["prompt_tokens"] == 10 + assert usage["completion_tokens"] == len(synthetic_ids) + assert usage["total_tokens"] == 10 + len(synthetic_ids) + + +@pytest.mark.asyncio +async def test_derender_chat_usage_default(client): + """Omitting prompt_tokens gives usage.prompt_tokens == 0.""" + gen_req = await _render_chat(client) + synthetic_ids = gen_req["token_ids"][:3] + + response = await client.post( + "/v1/chat/completions/derender", + json={ + "model": MODEL_NAME, + "generate_response": _make_generate_response(synthetic_ids), + }, + ) + assert response.status_code == 200 + usage = response.json()["usage"] + assert usage["prompt_tokens"] == 0 + + +@pytest.mark.asyncio +async def test_derender_chat_logprobs(client): + """token_id:N placeholders in content.token are resolved to real strings.""" + gen_req = await _render_chat(client) + synthetic_ids = gen_req["token_ids"][:3] + token_id = synthetic_ids[0] + + response = await client.post( + "/v1/chat/completions/derender", + json={ + "model": MODEL_NAME, + "generate_response": _make_generate_response( + synthetic_ids, + logprobs=_make_logprobs_with_placeholders(token_id), + ), + }, + ) + assert response.status_code == 200 + data = response.json() + logprobs = data["choices"][0]["logprobs"] + assert logprobs is not None + content = logprobs["content"] + assert content is not None and len(content) == 1 + token_str = content[0]["token"] + assert not token_str.startswith("token_id:"), ( + f"Placeholder was not resolved: {token_str!r}" + ) + + +@pytest.mark.asyncio +async def test_derender_chat_logprobs_bytes(client): + """Resolved logprob entries have bytes populated as list[int].""" + gen_req = await _render_chat(client) + synthetic_ids = gen_req["token_ids"][:3] + token_id = synthetic_ids[0] + + response = await client.post( + "/v1/chat/completions/derender", + json={ + "model": MODEL_NAME, + "generate_response": _make_generate_response( + synthetic_ids, + logprobs=_make_logprobs_with_placeholders(token_id), + ), + }, + ) + assert response.status_code == 200 + content = response.json()["choices"][0]["logprobs"]["content"] + bytes_field = content[0]["bytes"] + assert isinstance(bytes_field, list) + assert len(bytes_field) > 0 + assert all(isinstance(b, int) for b in bytes_field) + + +@pytest.mark.asyncio +async def test_derender_chat_top_logprobs(client): + """top_logprobs entries also have their placeholders resolved.""" + gen_req = await _render_chat(client) + synthetic_ids = gen_req["token_ids"][:3] + token_id = synthetic_ids[0] + + response = await client.post( + "/v1/chat/completions/derender", + json={ + "model": MODEL_NAME, + "generate_response": _make_generate_response( + synthetic_ids, + logprobs=_make_logprobs_with_placeholders(token_id), + ), + }, + ) + assert response.status_code == 200 + content = response.json()["choices"][0]["logprobs"]["content"] + top = content[0]["top_logprobs"] + assert len(top) == 1 + assert not top[0]["token"].startswith("token_id:"), ( + f"top_logprobs placeholder not resolved: {top[0]['token']!r}" + ) + + +@pytest.mark.asyncio +async def test_derender_chat_prompt_logprobs_passthrough(client): + """prompt_logprobs on GenerateResponse passes through unchanged.""" + gen_req = await _render_chat(client) + synthetic_ids = gen_req["token_ids"][:3] + # prompt_logprobs is a list[dict[int, Logprob] | None]; use None entries. + prompt_logprobs = [None, None] + + response = await client.post( + "/v1/chat/completions/derender", + json={ + "model": MODEL_NAME, + "generate_response": _make_generate_response( + synthetic_ids, prompt_logprobs=prompt_logprobs + ), + }, + ) + assert response.status_code == 200 + assert response.json()["prompt_logprobs"] == prompt_logprobs + + +@pytest.mark.asyncio +async def test_derender_chat_kv_transfer_params_passthrough(client): + """kv_transfer_params passes through to the ChatCompletionResponse.""" + gen_req = await _render_chat(client) + synthetic_ids = gen_req["token_ids"][:3] + kv = {"key": "value"} + + response = await client.post( + "/v1/chat/completions/derender", + json={ + "model": MODEL_NAME, + "generate_response": _make_generate_response( + synthetic_ids, kv_transfer_params=kv + ), + }, + ) + assert response.status_code == 200 + assert response.json()["kv_transfer_params"] == kv + + +@pytest.mark.asyncio +async def test_derender_chat_empty_token_ids(client): + """Empty token_ids list returns 400.""" + response = await client.post( + "/v1/chat/completions/derender", + json={ + "model": MODEL_NAME, + "generate_response": _make_generate_response([]), + }, + ) + assert response.status_code == 400 + + +@pytest.mark.asyncio +async def test_derender_chat_null_token_ids(client): + """Null token_ids returns 400.""" + response = await client.post( + "/v1/chat/completions/derender", + json={ + "model": MODEL_NAME, + "generate_response": _make_generate_response(None), + }, + ) + assert response.status_code == 400 + + +@pytest.mark.asyncio +async def test_derender_chat_unknown_model(client): + """Unknown model returns 404.""" + gen_req = await _render_chat(client) + synthetic_ids = gen_req["token_ids"][:3] + + response = await client.post( + "/v1/chat/completions/derender", + json={ + "model": "does-not-exist", + "generate_response": _make_generate_response(synthetic_ids), + }, + ) + assert response.status_code == 404 + + +# --------------------------------------------------------------------------- +# Completion derender tests +# --------------------------------------------------------------------------- + + +async def _render_completion(client: httpx.AsyncClient, prompt: str) -> dict: + """Render a completion prompt and return the first GenerateRequest dict.""" + resp = await client.post( + "/v1/completions/render", + json={"model": MODEL_NAME, "prompt": prompt}, + ) + assert resp.status_code == 200 + data = resp.json() + assert isinstance(data, list) and len(data) >= 1 + return data[0] + + +def _make_completion_generate_response( + token_ids: list[int], + request_id: str, + kv_transfer_params: dict | None = None, + logprobs: dict | None = None, +) -> dict: + return { + "request_id": request_id, + "choices": [ + { + "index": 0, + "token_ids": token_ids, + "finish_reason": "stop", + "logprobs": logprobs, + } + ], + "prompt_logprobs": None, + "kv_transfer_params": kv_transfer_params, + } + + +@pytest.mark.asyncio +async def test_derender_completion_roundtrip(client): + """Two prompts rendered, two GenerateResponses → two choices with indices 0, 1.""" + gr1 = await _render_completion(client, "Hello world") + gr2 = await _render_completion(client, "Goodbye world") + + ids1 = gr1["token_ids"][:4] + ids2 = gr2["token_ids"][:4] + + response = await client.post( + "/v1/completions/derender", + json={ + "model": MODEL_NAME, + "generate_responses": [ + _make_completion_generate_response(ids1, gr1["request_id"]), + _make_completion_generate_response(ids2, gr2["request_id"]), + ], + }, + ) + assert response.status_code == 200 + data = response.json() + assert data["object"] == "text_completion" + choices = data["choices"] + assert len(choices) == 2 + assert choices[0]["index"] == 0 + assert choices[1]["index"] == 1 + assert choices[0]["text"] + assert choices[1]["text"] + + +@pytest.mark.asyncio +async def test_derender_completion_usage_aggregation(client): + """prompt_tokens=[5, 10] is aggregated correctly into usage.""" + gr1 = await _render_completion(client, "Hello") + gr2 = await _render_completion(client, "World") + + ids1 = gr1["token_ids"][:3] + ids2 = gr2["token_ids"][:4] + + response = await client.post( + "/v1/completions/derender", + json={ + "model": MODEL_NAME, + "generate_responses": [ + _make_completion_generate_response(ids1, gr1["request_id"]), + _make_completion_generate_response(ids2, gr2["request_id"]), + ], + "prompt_tokens": [5, 10], + }, + ) + assert response.status_code == 200 + usage = response.json()["usage"] + assert usage["prompt_tokens"] == 15 + assert usage["completion_tokens"] == len(ids1) + len(ids2) + assert usage["total_tokens"] == 15 + len(ids1) + len(ids2) + + +@pytest.mark.asyncio +async def test_derender_completion_prompt_tokens_length_mismatch(client): + """len(prompt_tokens) != len(generate_responses) returns 400.""" + gr1 = await _render_completion(client, "Hello") + ids1 = gr1["token_ids"][:3] + + response = await client.post( + "/v1/completions/derender", + json={ + "model": MODEL_NAME, + "generate_responses": [ + _make_completion_generate_response(ids1, gr1["request_id"]), + ], + "prompt_tokens": [5, 10], + }, + ) + assert response.status_code == 400 + + +@pytest.mark.asyncio +async def test_derender_completion_empty_generate_responses(client): + """Empty generate_responses list returns 400.""" + response = await client.post( + "/v1/completions/derender", + json={"model": MODEL_NAME, "generate_responses": []}, + ) + assert response.status_code == 400 + + +@pytest.mark.asyncio +async def test_derender_completion_logprobs(client): + """token_id:N placeholders in logprobs are resolved; CompletionLogProbs + flat-list structure is returned with non-empty tokens and text_offsets.""" + gr1 = await _render_completion(client, "Hello world") + ids1 = gr1["token_ids"][:3] + token_id = ids1[0] + + response = await client.post( + "/v1/completions/derender", + json={ + "model": MODEL_NAME, + "generate_responses": [ + _make_completion_generate_response( + ids1, + gr1["request_id"], + logprobs=_make_logprobs_with_placeholders(token_id), + ), + ], + }, + ) + assert response.status_code == 200 + logprobs = response.json()["choices"][0]["logprobs"] + assert logprobs is not None + tokens = logprobs["tokens"] + assert len(tokens) == 1 + assert not tokens[0].startswith("token_id:"), ( + f"Placeholder was not resolved: {tokens[0]!r}" + ) + assert len(logprobs["token_logprobs"]) == 1 + assert isinstance(logprobs["token_logprobs"][0], float) + assert len(logprobs["text_offset"]) == 1 + assert logprobs["text_offset"][0] == 0 + + +@pytest.mark.asyncio +async def test_derender_completion_kv_transfer_params_passthrough(client): + """kv_transfer_params passes through to CompletionResponse.""" + gr1 = await _render_completion(client, "Hello") + ids1 = gr1["token_ids"][:3] + kv = {"node": "abc"} + + response = await client.post( + "/v1/completions/derender", + json={ + "model": MODEL_NAME, + "generate_responses": [ + _make_completion_generate_response( + ids1, gr1["request_id"], kv_transfer_params=kv + ), + ], + }, + ) + assert response.status_code == 200 + assert response.json()["kv_transfer_params"] == kv diff --git a/tests/entrypoints/serve/utils/test_ssl_cert_refresher.py b/tests/entrypoints/serve/utils/test_ssl_cert_refresher.py index 57a856ce118f..8f5251374a6b 100644 --- a/tests/entrypoints/serve/utils/test_ssl_cert_refresher.py +++ b/tests/entrypoints/serve/utils/test_ssl_cert_refresher.py @@ -41,6 +41,28 @@ def touch_file(path: str) -> None: Path(path).touch() +async def wait_for_counts( + ssl_context: MockSSLContext, + *, + cert_chain_count: int, + ca_count: int, + timeout: float = 5.0, +) -> None: + deadline = asyncio.get_running_loop().time() + timeout + while True: + if ( + ssl_context.load_cert_chain_count >= cert_chain_count + and ssl_context.load_ca_count >= ca_count + ): + return + + if asyncio.get_running_loop().time() >= deadline: + assert ssl_context.load_cert_chain_count >= cert_chain_count + assert ssl_context.load_ca_count >= ca_count + + await asyncio.sleep(0.05) + + @pytest.mark.asyncio async def test_ssl_refresher(): ssl_context = MockSSLContext() @@ -53,20 +75,28 @@ async def test_ssl_refresher(): assert ssl_context.load_ca_count == 0 touch_file(key_path) - await asyncio.sleep(1) - assert ssl_context.load_cert_chain_count == 1 + await wait_for_counts( + ssl_context, + cert_chain_count=1, + ca_count=0, + ) assert ssl_context.load_ca_count == 0 touch_file(cert_path) touch_file(ca_path) - await asyncio.sleep(1) - assert ssl_context.load_cert_chain_count == 2 - assert ssl_context.load_ca_count == 1 + await wait_for_counts( + ssl_context, + cert_chain_count=2, + ca_count=1, + ) ssl_refresher.stop() + await asyncio.sleep(0) + cert_chain_count = ssl_context.load_cert_chain_count + ca_count = ssl_context.load_ca_count touch_file(cert_path) touch_file(ca_path) await asyncio.sleep(1) - assert ssl_context.load_cert_chain_count == 2 - assert ssl_context.load_ca_count == 1 + assert ssl_context.load_cert_chain_count == cert_chain_count + assert ssl_context.load_ca_count == ca_count diff --git a/tests/entrypoints/speech_to_text/test_upload_size_limit.py b/tests/entrypoints/speech_to_text/test_upload_size_limit.py new file mode 100644 index 000000000000..5d38e7691948 --- /dev/null +++ b/tests/entrypoints/speech_to_text/test_upload_size_limit.py @@ -0,0 +1,142 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Regression tests for the speech-to-text upload size pre-check. + +These tests verify that over-limit audio uploads are rejected *before* +the full file is materialized into memory, closing the vulnerability +where vLLM would allocate memory proportional to an oversized upload +before enforcing the VLLM_MAX_AUDIO_CLIP_FILESIZE_MB limit. +""" + +from unittest.mock import AsyncMock, patch + +import pytest + +from vllm.entrypoints.speech_to_text.base.utils import read_upload_with_limit +from vllm.exceptions import VLLMValidationError + + +def _make_upload_file(data: bytes, *, size: int | None = None) -> AsyncMock: + """Create a mock UploadFile that yields data in chunks.""" + mock = AsyncMock() + mock.size = size + + offset = 0 + + async def _read(n: int = -1): + nonlocal offset + if n <= 0: + chunk = data[offset:] + offset = len(data) + return chunk + chunk = data[offset : offset + n] + offset += len(chunk) + return chunk + + mock.read = AsyncMock(side_effect=_read) + return mock + + +@pytest.mark.asyncio +async def test_rejects_oversized_upload_via_content_length(): + """File is rejected early when file.size exceeds the limit.""" + max_mb = 1 + oversized_bytes = max_mb * 1024 * 1024 + 1 + + upload = _make_upload_file(b"", size=oversized_bytes) + + with pytest.raises(VLLMValidationError, match="Maximum file size exceeded"): + await read_upload_with_limit(upload, max_size_mb=max_mb) + + upload.read.assert_not_called() + + +@pytest.mark.asyncio +async def test_rejects_oversized_upload_via_chunked_read(): + """File is rejected mid-read without materializing the full content.""" + max_mb = 1 + max_bytes = max_mb * 1024 * 1024 + oversized_data = b"\x00" * (max_bytes + 1024) + + upload = _make_upload_file(oversized_data, size=None) + + with pytest.raises(VLLMValidationError, match="Maximum file size exceeded"): + await read_upload_with_limit(upload, max_size_mb=max_mb) + + +@pytest.mark.asyncio +async def test_accepts_file_within_limit(): + """File within the limit is read successfully.""" + max_mb = 1 + data = b"\x00" * (512 * 1024) # 512 KiB, well under 1 MB + + upload = _make_upload_file(data, size=len(data)) + result = await read_upload_with_limit(upload, max_size_mb=max_mb) + + assert result == data + + +@pytest.mark.asyncio +async def test_accepts_file_at_exact_limit(): + """File exactly at the limit boundary is accepted.""" + max_mb = 1 + max_bytes = max_mb * 1024 * 1024 + data = b"\x00" * max_bytes + + upload = _make_upload_file(data, size=len(data)) + result = await read_upload_with_limit(upload, max_size_mb=max_mb) + + assert result == data + + +@pytest.mark.asyncio +async def test_rejects_at_one_byte_over_limit(): + """File one byte over the limit is rejected.""" + max_mb = 1 + max_bytes = max_mb * 1024 * 1024 + data = b"\x00" * (max_bytes + 1) + + upload = _make_upload_file(data, size=None) + + with pytest.raises(VLLMValidationError, match="Maximum file size exceeded"): + await read_upload_with_limit(upload, max_size_mb=max_mb) + + +@pytest.mark.asyncio +async def test_uses_env_default_when_no_limit_specified(): + """Uses VLLM_MAX_AUDIO_CLIP_FILESIZE_MB when max_size_mb is not given.""" + with patch("vllm.entrypoints.speech_to_text.base.utils.envs") as mock_envs: + mock_envs.VLLM_MAX_AUDIO_CLIP_FILESIZE_MB = 2 + max_bytes = 2 * 1024 * 1024 + oversized_data = b"\x00" * (max_bytes + 1) + + upload = _make_upload_file(oversized_data, size=None) + + with pytest.raises(VLLMValidationError, match="Maximum file size exceeded"): + await read_upload_with_limit(upload) + + +@pytest.mark.asyncio +async def test_chunked_read_does_not_fully_materialize(): + """Verify that for large oversized files, we stop reading early. + + The function reads in 64 KiB chunks and aborts once the accumulated + size exceeds the limit. We confirm that far fewer read calls were made + than would be required to fully materialize the file. + """ + max_mb = 1 + max_bytes = max_mb * 1024 * 1024 + large_size = max_bytes * 10 # 10x the limit + data = b"\x00" * large_size + + upload = _make_upload_file(data, size=None) + + with pytest.raises(VLLMValidationError): + await read_upload_with_limit(upload, max_size_mb=max_mb) + + chunk_size = 64 * 1024 + calls_for_full_read = large_size // chunk_size + 1 + calls_to_exceed_limit = max_bytes // chunk_size + 1 + actual_calls = upload.read.call_count + assert actual_calls <= calls_to_exceed_limit + 1 + assert actual_calls < calls_for_full_read diff --git a/tests/fusion/__init__.py b/tests/fusion/__init__.py new file mode 100644 index 000000000000..208f01a7cb5e --- /dev/null +++ b/tests/fusion/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/tests/fusion/test_quant_activation_contract.py b/tests/fusion/test_quant_activation_contract.py new file mode 100644 index 000000000000..48d492b8d2ee --- /dev/null +++ b/tests/fusion/test_quant_activation_contract.py @@ -0,0 +1,131 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Contract tests for the QuantizedActivation linear-kernel integration.""" + +import pytest +import torch + +from vllm.model_executor.kernels.linear import ( + _POSSIBLE_FP8_BLOCK_KERNELS, + _POSSIBLE_FP8_KERNELS, + _POSSIBLE_INT8_KERNELS, + _POSSIBLE_NVFP4_KERNELS, +) +from vllm.model_executor.kernels.linear.nvfp4.base import ( + NvFp4LinearKernel, + NvFp4LinearLayerConfig, +) +from vllm.model_executor.kernels.linear.nvfp4.flashinfer import ( + FlashInferCutlassNvFp4LinearKernel, + FlashInferTrtllmNvFp4LinearKernel, +) +from vllm.model_executor.kernels.linear.scaled_mm.cutlass import ( + CutlassFP8ScaledMMLinearKernel, +) +from vllm.model_executor.kernels.linear.scaled_mm.flashinfer import ( + FlashInferFP8ScaledMMLinearKernel, +) +from vllm.model_executor.kernels.linear.scaled_mm.ScaledMMLinearKernel import ( + FP8ScaledMMLinearLayerConfig, + Int8ScaledMMLinearKernel, + Int8ScaledMMLinearLayerConfig, +) +from vllm.model_executor.layers.fusion.quant_activation import ( + QuantizedActivation, + as_quantized_activation, + expose_input_quant_key, +) +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + kFp8StaticTensorSym, + kNvfp4Dynamic, +) +from vllm.platforms import current_platform + +# The only backends that consume a pre-quantized activation. +SUPPORTING = { + CutlassFP8ScaledMMLinearKernel, + FlashInferFP8ScaledMMLinearKernel, + FlashInferCutlassNvFp4LinearKernel, +} + + +def _all_kernel_classes() -> list[type]: + seen: dict[type, None] = {} + for registry in ( + _POSSIBLE_FP8_KERNELS, + _POSSIBLE_FP8_BLOCK_KERNELS, + _POSSIBLE_INT8_KERNELS, + _POSSIBLE_NVFP4_KERNELS, + ): + for kernels in registry.values(): + for cls in kernels: + seen.setdefault(cls, None) + return list(seen) + + +def _probe(cls: type): + """A bare kernel instance with a plausible config, so input_quant_key() + can be queried without the hardware-gated constructor.""" + obj = cls.__new__(cls) # type: ignore[call-overload] + if issubclass(cls, NvFp4LinearKernel): + obj.config = NvFp4LinearLayerConfig() + elif issubclass(cls, Int8ScaledMMLinearKernel): + obj.config = Int8ScaledMMLinearLayerConfig( + is_static_input_scheme=True, is_channelwise=False, input_symmetric=True + ) + else: + obj.config = FP8ScaledMMLinearLayerConfig( + weight_quant_key=kFp8StaticTensorSym, + activation_quant_key=kFp8StaticTensorSym, + weight_shape=(16, 16), + input_dtype=torch.bfloat16, + out_dtype=torch.bfloat16, + ) + return obj + + +def _resolved_apply_weights(cls: type): + for base in cls.__mro__: + if "apply_weights" in base.__dict__: + return base.__dict__["apply_weights"] + raise AssertionError(f"{cls.__name__} has no apply_weights in its MRO") + + +def test_only_known_backends_support_prequantized_input(): + declarers = {c for c in _all_kernel_classes() if _probe(c).input_quant_key()} + assert declarers == SUPPORTING + + +def test_supporting_backend_declares_consume_via_helper(): + for cls in SUPPORTING: + fn = _resolved_apply_weights(cls) + assert "as_quantized_activation" in fn.__code__.co_names, cls.__name__ + + +def test_bridge_marks_supporting_and_skips_others(): + supported = _probe(FlashInferCutlassNvFp4LinearKernel) + layer = torch.nn.Module() + expose_input_quant_key(layer, supported) + assert layer.input_quant_key == kNvfp4Dynamic + + unsupported = _probe(FlashInferTrtllmNvFp4LinearKernel) + assert unsupported.input_quant_key() is None + layer = torch.nn.Module() + expose_input_quant_key(layer, unsupported) + assert not hasattr(layer, "input_quant_key") + + +def test_as_quantized_activation_validates_key(): + qa = QuantizedActivation( + data=torch.zeros(2, 4, dtype=current_platform.fp8_dtype()), + scale=torch.tensor(1.0), + orig_dtype=torch.bfloat16, + orig_shape=torch.Size([2, 4]), + quant_key=kFp8StaticTensorSym, + ) + with pytest.raises(AssertionError): + as_quantized_activation(qa, kNvfp4Dynamic) + with pytest.raises(AssertionError): + as_quantized_activation(qa, None) + assert as_quantized_activation(torch.zeros(2, 4), kFp8StaticTensorSym) is None + assert as_quantized_activation(qa, kFp8StaticTensorSym) is qa diff --git a/tests/kernels/attention/test_cpu_attn.py b/tests/kernels/attention/test_cpu_attn.py index c39395025516..e296c226d709 100644 --- a/tests/kernels/attention/test_cpu_attn.py +++ b/tests/kernels/attention/test_cpu_attn.py @@ -25,7 +25,6 @@ if torch.cpu._is_amx_tile_supported(): torch.cpu._init_amx() - NUM_HEADS = [ (4, 4), (8, 2), @@ -43,6 +42,11 @@ [(2345, 2345), (5, 5), (3, 16), (134, 5131)], # prefill batch [(992, 2456), (1, 1234), (98, 1145), (1, 4162), (2345, 2345)], # mixed batch ] +_FP8_ATOL = {"fp8_e4m3": 0.2, "fp8_e5m2": 0.3} +_FP8_RTOL = 0.1 +ENCODER_SEQ_LENS = [ + [1, 678, 2367, 145, 4162, 36, 7812], +] def get_attn_isa( @@ -61,10 +65,7 @@ def get_attn_isa( # rand number generation takes too much time, cache rand tensors @functools.lru_cache(maxsize=128, typed=False) -def tensor_cache( - elem_num: int, - dtype: torch.dtype, -) -> torch.Tensor: +def tensor_cache(elem_num: int, dtype: torch.dtype, tag: str = "none") -> torch.Tensor: tensor = torch.randn(elem_num, dtype=dtype) return tensor @@ -106,6 +107,7 @@ def ref_paged_attn( soft_cap: float | None = None, alibi_slopes: torch.Tensor | None = None, s_aux: torch.Tensor | None = None, + dynamic_causal: list[bool] | None = None, ) -> torch.Tensor: num_seqs = len(query_lens) block_tables = block_tables.cpu().numpy() @@ -141,17 +143,30 @@ def ref_paged_attn( v = torch.repeat_interleave(v, q.shape[1] // v.shape[1], dim=1) attn = torch.einsum("qhd,khd->hqk", q, k).float() empty_mask = torch.ones(query_len, kv_len) - mask = torch.triu(empty_mask, diagonal=kv_len - query_len + 1).bool() - if sliding_window is not None: - sliding_window_mask = ( - torch.triu( - empty_mask, diagonal=kv_len - (query_len + sliding_window) + 1 + if dynamic_causal is None or dynamic_causal[i]: + mask = torch.triu(empty_mask, diagonal=kv_len - query_len + 1).bool() + if sliding_window is not None: + sliding_window_mask = ( + torch.triu( + empty_mask, diagonal=kv_len - (query_len + sliding_window) + 1 + ) + .bool() + .logical_not() ) - .bool() - .logical_not() - ) - mask |= sliding_window_mask + mask |= sliding_window_mask + else: + if sliding_window is not None: + mask = ( + torch.triu( + empty_mask, diagonal=1 - sliding_window + kv_len - query_len + ).bool() + ^ torch.triu( + empty_mask, diagonal=sliding_window + kv_len - query_len + ).bool() + ).logical_not() + else: + mask = empty_mask.logical_not() if soft_cap is not None: attn = soft_cap * torch.tanh(attn / soft_cap) @@ -183,8 +198,217 @@ def ref_paged_attn( return torch.cat(outputs, dim=0) -_FP8_ATOL = {"fp8_e4m3": 0.2, "fp8_e5m2": 0.3} -_FP8_RTOL = 0.1 +def ref_varlen_encoder_attn( + query: torch.Tensor, # [token, q_head_num, head_dim] + key: torch.Tensor, # [token, kv_head_num, head_dim] + value: torch.Tensor, + seq_lens: list[int], + scale: float, + sliding_window: int | None = None, +) -> torch.Tensor: + num_seqs = len(seq_lens) + dtype = query.dtype + + output = torch.empty_like(query) + + start_idx = 0 + for i in range(num_seqs): + seq_len = seq_lens[i] + q = query[start_idx : start_idx + seq_len].float() + k = key[start_idx : start_idx + seq_len].float() + v = value[start_idx : start_idx + seq_len].float() + q *= scale + + if q.shape[1] != k.shape[1]: + k = torch.repeat_interleave(k, q.shape[1] // k.shape[1], dim=1) + v = torch.repeat_interleave(v, q.shape[1] // v.shape[1], dim=1) + attn = torch.einsum("qhd,khd->hqk", q, k).float() + empty_mask = torch.ones(seq_len, seq_len) + if sliding_window is not None: + mask = ( + torch.triu(empty_mask, diagonal=1 - sliding_window).bool() + ^ torch.triu(empty_mask, diagonal=sliding_window).bool() + ).logical_not() + else: + mask = empty_mask.logical_not() + + attn.masked_fill_(mask, float("-inf")) + attn = torch.softmax(attn, dim=-1) + out = torch.einsum("hqk,khd->qhd", attn, v).to(dtype=dtype) + output[start_idx : start_idx + seq_len].copy_(out) + + start_idx += seq_len + + return output + + +@torch.inference_mode() +def varlen_encoder_attention( + seq_lens: list[int], + num_heads: tuple[int, int], + head_size: int, + sliding_window: int | None, + dtype: torch.dtype, + block_size: int, + isa: str, +) -> None: + set_random_seed(0) + num_seqs = len(seq_lens) + num_query_heads = num_heads[0] + num_kv_heads = num_heads[1] + assert num_query_heads % num_kv_heads == 0 + scale = head_size**-0.5 + token_num = sum(seq_lens) + + seq_lens_tensor = torch.tensor(seq_lens, dtype=torch.int32) + query_start_loc = torch.zeros(num_seqs, dtype=torch.int32) + torch.cumsum(seq_lens_tensor[:-1], 0, out=query_start_loc[1:]) + block_nums = (seq_lens_tensor + block_size - 1) // block_size + start_block_ids = torch.zeros_like(seq_lens_tensor) + torch.cumsum(block_nums[:-1], 0, out=start_block_ids[1:]) + total_block_num: int = block_nums.sum().item() + max_block_num = block_nums.max().item() + block_offsets = torch.arange(0, max_block_num, dtype=torch.int32) + encoder_block_table = start_block_ids[:, None] + block_offsets[None, :] + slot_mapping_list = [] + slot_start_idx = 0 + for i in range(num_seqs): + block_num = block_nums[i].item() + seq_len = seq_lens[i] + slot_mapping_list.append(torch.arange(slot_start_idx, slot_start_idx + seq_len)) + slot_start_idx += block_num * block_size + slot_mapping = torch.cat(slot_mapping_list) + + query = tensor_cache( + elem_num=token_num * num_query_heads * head_size, + dtype=dtype, + tag="query", + ) + query = query.view( + token_num, + num_query_heads, + head_size, + ) + + key_value = tensor_cache( + elem_num=2 * token_num * num_kv_heads * head_size, + dtype=dtype, + tag="kv", + ) + key_value = key_value.view( + 2, + token_num, + num_kv_heads, + head_size, + ) + key, value = key_value.unbind(0) + + # KV cache for CPU attention + packed_key_value_cache = torch.zeros( + total_block_num, num_kv_heads, block_size, head_size * 2, dtype=dtype + ) + packed_key_value_cache = packed_key_value_cache.view( + (total_block_num, num_kv_heads, block_size * 2, -1) + ) + packed_key_cache, packed_value_cache = packed_key_value_cache.chunk(2, dim=2) + + cu_query_lens = torch.tensor([0] + seq_lens, dtype=torch.int32).cumsum( + dim=0, dtype=torch.int32 + ) + kv_lens_tensor = torch.tensor(seq_lens, dtype=torch.int32) + + # use reshape_and_cache to pack key_cache and value_cache + cpu_attn_reshape_and_cache( + key=key.view(-1, num_kv_heads, head_size), + value=value.view(-1, num_kv_heads, head_size), + key_cache=packed_key_cache, + value_cache=packed_value_cache, + slot_mapping=slot_mapping, + isa=isa, + ) + + metadata = cpu_attn_get_scheduler_metadata( + num_reqs=num_seqs, + num_heads=num_query_heads, + num_kv_heads=num_kv_heads, + head_dim=head_size, + seq_lens=kv_lens_tensor, + dtype=dtype, + query_start_loc=cu_query_lens, + causal=False, + sliding_window_size=sliding_window if sliding_window is not None else -1, + isa=isa, + enable_kv_split=False, + ) + + out_without_split = torch.empty_like(query) + cpu_attention_with_kv_cache( + query=query, + key_cache=packed_key_cache, + value_cache=packed_value_cache, + output=out_without_split, + query_start_loc=cu_query_lens, + seq_lens=kv_lens_tensor, + scale=scale, + causal=False, + alibi_slopes=None, + sliding_window=sliding_window if sliding_window is not None else -1, + block_table=encoder_block_table, + softcap=0, + scheduler_metadata=metadata, + s_aux=None, + ) + + metadata = cpu_attn_get_scheduler_metadata( + num_reqs=num_seqs, + num_heads=num_query_heads, + num_kv_heads=num_kv_heads, + head_dim=head_size, + seq_lens=kv_lens_tensor, + dtype=dtype, + query_start_loc=cu_query_lens, + causal=False, + sliding_window_size=sliding_window if sliding_window is not None else -1, + isa=isa, + enable_kv_split=True, + ) + + out_with_split = torch.empty_like(query) + cpu_attention_with_kv_cache( + query=query, + key_cache=packed_key_cache, + value_cache=packed_value_cache, + output=out_with_split, + query_start_loc=cu_query_lens, + seq_lens=kv_lens_tensor, + scale=scale, + causal=False, + alibi_slopes=None, + sliding_window=sliding_window if sliding_window is not None else -1, + block_table=encoder_block_table, + softcap=0, + scheduler_metadata=metadata, + s_aux=None, + ) + + ref_output = ref_varlen_encoder_attn( + query=query, + key=key, + value=value, + seq_lens=seq_lens, + scale=scale, + sliding_window=sliding_window, + ) + atol, rtol = 1.5e-2, 1e-2 + + ( + torch.testing.assert_close(out_with_split, ref_output, atol=atol, rtol=rtol), + f"{torch.max(torch.abs(out_with_split - ref_output))}", + ) + ( + torch.testing.assert_close(out_without_split, ref_output, atol=atol, rtol=rtol), + f"{torch.max(torch.abs(out_without_split - ref_output))}", + ) @torch.inference_mode() @@ -203,6 +427,7 @@ def varlen_with_paged_kv( kv_cache_dtype: str = "auto", k_scale: float = 1.0, v_scale: float = 1.0, + dynamic_causal: list[bool] | None = None, ) -> None: set_random_seed(0) num_seqs = len(seq_lens) @@ -212,9 +437,13 @@ def varlen_with_paged_kv( num_kv_heads = num_heads[1] assert num_query_heads % num_kv_heads == 0 max_kv_len = max(kv_lens) - window_size = (sliding_window - 1, 0) if sliding_window is not None else (-1, -1) scale = head_size**-0.5 token_num = sum(query_lens) + dynamic_causal_tensor = ( + torch.tensor(dynamic_causal, dtype=torch.bool) + if dynamic_causal is not None + else None + ) # for n heads the set of slopes is the geometric sequence that starts # 2^(-8/n) @@ -300,10 +529,11 @@ def varlen_with_paged_kv( seq_lens=kv_lens_tensor, dtype=dtype, query_start_loc=cu_query_lens, - causal=True, + causal=dynamic_causal is None, sliding_window_size=sliding_window if sliding_window is not None else -1, isa=isa, enable_kv_split=False, + dynamic_causal=dynamic_causal_tensor, ) out_without_split = torch.empty_like(query) @@ -315,13 +545,14 @@ def varlen_with_paged_kv( query_start_loc=cu_query_lens, seq_lens=kv_lens_tensor, scale=scale, - causal=True, + causal=dynamic_causal is None, alibi_slopes=alibi_slopes, - sliding_window=window_size, + sliding_window=sliding_window if sliding_window is not None else -1, block_table=block_tables, softcap=soft_cap if soft_cap is not None else 0, scheduler_metadata=metadata, s_aux=s_aux, + dynamic_causal=dynamic_causal_tensor, **fp8_kwargs, ) @@ -333,10 +564,11 @@ def varlen_with_paged_kv( seq_lens=kv_lens_tensor, dtype=dtype, query_start_loc=cu_query_lens, - causal=True, + causal=dynamic_causal is None, sliding_window_size=sliding_window if sliding_window is not None else -1, isa=isa, enable_kv_split=True, + dynamic_causal=dynamic_causal_tensor, ) out_with_split = torch.empty_like(query) @@ -348,13 +580,14 @@ def varlen_with_paged_kv( query_start_loc=cu_query_lens, seq_lens=kv_lens_tensor, scale=scale, - causal=True, + causal=dynamic_causal is None, alibi_slopes=alibi_slopes, - sliding_window=window_size, + sliding_window=sliding_window if sliding_window is not None else -1, block_table=block_tables, softcap=soft_cap if soft_cap is not None else 0, scheduler_metadata=metadata, s_aux=s_aux, + dynamic_causal=dynamic_causal_tensor, **fp8_kwargs, ) @@ -382,13 +615,14 @@ def varlen_with_paged_kv( query_start_loc=cu_query_lens, seq_lens=kv_lens_tensor, scale=scale, - causal=True, + causal=dynamic_causal is None, alibi_slopes=alibi_slopes, - sliding_window=window_size, + sliding_window=sliding_window if sliding_window is not None else -1, block_table=block_tables, softcap=soft_cap if soft_cap is not None else 0, scheduler_metadata=metadata, s_aux=s_aux, + dynamic_causal=dynamic_causal_tensor, ) atol = _FP8_ATOL[kv_cache_dtype] rtol = _FP8_RTOL @@ -405,6 +639,7 @@ def varlen_with_paged_kv( soft_cap=soft_cap, alibi_slopes=alibi_slopes, s_aux=s_aux, + dynamic_causal=dynamic_causal, ) atol, rtol = 1.5e-2, 1e-2 @@ -418,6 +653,71 @@ def varlen_with_paged_kv( ) +@pytest.mark.parametrize("seq_lens", ENCODER_SEQ_LENS) +@pytest.mark.parametrize("num_heads", NUM_HEADS) +@pytest.mark.parametrize("head_size", HEAD_SIZES) +@pytest.mark.parametrize( + "block_size", + [ + 128, + ], +) +@pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) +@pytest.mark.parametrize("dtype", QTYPES) +@pytest.mark.parametrize("isa", ["vec"]) +def test_varlen_encoder_attention_vec( + seq_lens: list[int], + num_heads: tuple[int, int], + head_size: int, + sliding_window: int | None, + dtype: torch.dtype, + block_size: int, + isa: str, +) -> None: + varlen_encoder_attention( + seq_lens=seq_lens, + num_heads=num_heads, + head_size=head_size, + sliding_window=sliding_window, + dtype=dtype, + block_size=block_size, + isa=isa, + ) + + +@pytest.mark.parametrize("seq_lens", ENCODER_SEQ_LENS) +@pytest.mark.parametrize("num_heads", NUM_HEADS) +@pytest.mark.parametrize("head_size", HEAD_SIZES) +@pytest.mark.parametrize( + "block_size", + [ + 128, + ], +) +@pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) +@pytest.mark.parametrize("dtype", [torch.bfloat16]) +@pytest.mark.parametrize("isa", ["amx"]) +@pytest.mark.skipif(not torch.cpu._is_amx_tile_supported(), reason="no AMX support.") +def test_varlen_encoder_attention_amx( + seq_lens: list[int], + num_heads: tuple[int, int], + head_size: int, + sliding_window: int | None, + dtype: torch.dtype, + block_size: int, + isa: str, +) -> None: + varlen_encoder_attention( + seq_lens=seq_lens, + num_heads=num_heads, + head_size=head_size, + sliding_window=sliding_window, + dtype=dtype, + block_size=block_size, + isa=isa, + ) + + @pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8_e4m3", "fp8_e5m2"]) @pytest.mark.parametrize("seq_lens", SEQ_LENS) @pytest.mark.parametrize("num_heads", NUM_HEADS) @@ -755,3 +1055,58 @@ def test_varlen_with_paged_kv_sink( isa=isa, kv_cache_dtype=kv_cache_dtype, ) + + +@pytest.mark.parametrize( + "kv_cache_dtype", + [ + "auto", + ], +) +@pytest.mark.parametrize("seq_lens", SEQ_LENS) +@pytest.mark.parametrize("num_heads", NUM_HEADS) +@pytest.mark.parametrize( + "head_size", + [ + 128, + ], +) +@pytest.mark.parametrize("block_size", [96, 128]) +@pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS) +@pytest.mark.parametrize("dtype", [torch.bfloat16]) +@pytest.mark.parametrize("soft_cap", [None]) +@pytest.mark.parametrize("num_blocks", NUM_BLOCKS) +@pytest.mark.parametrize("use_alibi", [False]) +@pytest.mark.parametrize("use_sink", [False]) +@pytest.mark.parametrize("isa", ["amx"]) +@pytest.mark.skipif(not torch.cpu._is_amx_tile_supported(), reason="no AMX support.") +def test_varlen_with_paged_kv_dynamic_causal( + seq_lens: list[tuple[int, int]], + num_heads: tuple[int, int], + head_size: int, + sliding_window: int | None, + dtype: torch.dtype, + block_size: int, + soft_cap: float | None, + num_blocks: int, + use_alibi: bool, + use_sink: bool, + isa: str, + kv_cache_dtype: str, +) -> None: + dynamic_causal = [bool(i % 2) for i in range(len(seq_lens))] + varlen_with_paged_kv( + seq_lens=seq_lens, + num_heads=num_heads, + head_size=head_size, + sliding_window=sliding_window, + dtype=dtype, + block_size=block_size, + soft_cap=soft_cap, + num_blocks=num_blocks, + use_alibi=use_alibi, + use_sink=use_sink, + isa=isa, + kv_cache_dtype=kv_cache_dtype, + dynamic_causal=dynamic_causal, + ) diff --git a/tests/kernels/attention/test_flashmla_sparse.py b/tests/kernels/attention/test_flashmla_sparse.py index d92dabe9d3ef..010c44797665 100644 --- a/tests/kernels/attention/test_flashmla_sparse.py +++ b/tests/kernels/attention/test_flashmla_sparse.py @@ -122,3 +122,171 @@ def test_sparse_flashmla_prefill_smoke(): assert out.shape == (s_q, h_q, d_v) assert max_logits.shape == (s_q, h_q) assert lse.shape == (s_q, h_q) + + +def test_deepseek_v4_prefill_chunk_planning_expands_for_short_sequences(): + from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata + + metadata = DeepseekSparseSWAMetadata( + block_table=torch.empty(0, dtype=torch.int32), + slot_mapping=torch.empty(0, dtype=torch.int32), + block_size=64, + num_prefills=5, + prefill_seq_lens_cpu=torch.tensor([80, 96, 112, 128, 144], dtype=torch.int32), + prefill_query_lens_cpu=torch.tensor([4, 4, 4, 4, 4], dtype=torch.int32), + prefill_window_size=64, + prefill_max_model_len=1024, + prefill_max_num_batched_tokens=128, + ) + + chunk_plan = metadata.get_prefill_chunk_plan(compress_ratio=4, prefill_chunk_size=4) + + # the adaptive plan keeps all 5 in one chunk + assert chunk_plan == [(0, 5, 36, 103)] + + +def test_flashinfer_sparse_indices_cache(monkeypatch): + from vllm.models.deepseek_v4.nvidia import flashinfer_sparse as flashinfer_mod + from vllm.models.deepseek_v4.sparse_mla import DeepseekV4FlashMLAMetadata + from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata + + builder_calls = 0 + + def fake_build(*args, **kwargs): + nonlocal builder_calls + builder_calls += 1 + return ( + torch.tensor([[builder_calls]], dtype=torch.int32), + torch.tensor([builder_calls], dtype=torch.int32), + ) + + monkeypatch.setattr( + flashinfer_mod, "build_flashinfer_mixed_sparse_indices", fake_build + ) + + def make_attn(compress_ratio: int, topk_width: int): + attn = object.__new__(flashinfer_mod.DeepseekV4FlashInferMLAAttention) + attn.compress_ratio = compress_ratio + attn.window_size = 4 + attn.topk_indices_buffer = torch.tensor( + [[0, 1], [2, 3], [4, 5]], dtype=torch.int32 + )[:, :topk_width] + return attn + + def make_swa_metadata(): + return DeepseekSparseSWAMetadata( + block_table=torch.tensor([[0, 1], [2, 3]], dtype=torch.int32), + slot_mapping=torch.tensor([0, 1], dtype=torch.int64), + block_size=64, + seq_lens=torch.tensor([8, 10], dtype=torch.int32), + query_start_loc=torch.tensor([0, 1, 3], dtype=torch.int32), + query_start_loc_cpu=torch.tensor([0, 1, 3], dtype=torch.int32), + token_to_req_indices=torch.tensor([0, 1, 1], dtype=torch.int32), + decode_swa_indices=torch.tensor([[5, 6, -1, -1]], dtype=torch.int32), + decode_swa_lens=torch.tensor([2], dtype=torch.int32), + is_valid_token=torch.tensor([True], dtype=torch.bool), + num_decodes=1, + num_prefills=1, + num_decode_tokens=1, + num_prefill_tokens=2, + ) + + def make_flashmla_metadata(): + return DeepseekV4FlashMLAMetadata( + num_reqs=2, + max_query_len=2, + max_seq_len=10, + num_actual_tokens=3, + query_start_loc=torch.tensor([0, 1, 3], dtype=torch.int32), + slot_mapping=torch.tensor([0, 1, 2], dtype=torch.int64), + block_table=torch.tensor([[0, 1], [2, 3]], dtype=torch.int32), + req_id_per_token=torch.tensor([0, 1, 1], dtype=torch.int32), + block_size=256, + topk_tokens=2, + c128a_global_decode_topk_indices=torch.tensor( + [[[9, 10]]], dtype=torch.int32 + ), + c128a_decode_topk_lens=torch.tensor([2], dtype=torch.int32), + c128a_prefill_topk_indices=torch.tensor( + [[0, 1], [1, 2]], dtype=torch.int32 + ), + ) + + swa_attn = make_attn(1, 0) + swa_metadata = make_swa_metadata() + _, _, sparse_indices_first, sparse_lens_first = ( + swa_attn._build_sparse_index_metadata( + kv_cache=None, + swa_k_cache=torch.empty((1, 64, 512), dtype=torch.bfloat16), + swa_metadata=swa_metadata, + attn_metadata=None, + swa_only=True, + ) + ) + _, _, sparse_indices_second, sparse_lens_second = ( + swa_attn._build_sparse_index_metadata( + kv_cache=None, + swa_k_cache=torch.empty((1, 64, 512), dtype=torch.bfloat16), + swa_metadata=swa_metadata, + attn_metadata=None, + swa_only=True, + ) + ) + assert builder_calls == 1 + assert sparse_indices_first is sparse_indices_second + assert sparse_lens_first is sparse_lens_second + + c128a_attn = make_attn(128, 2) + c128a_metadata = make_swa_metadata() + c128a_flashmla_md = make_flashmla_metadata() + _, _, sparse_indices_first, sparse_lens_first = ( + c128a_attn._build_sparse_index_metadata( + kv_cache=torch.empty((1, 2, 512), dtype=torch.bfloat16), + swa_k_cache=torch.empty((1, 64, 512), dtype=torch.bfloat16), + swa_metadata=c128a_metadata, + attn_metadata=c128a_flashmla_md, + swa_only=False, + ) + ) + _, _, sparse_indices_second, sparse_lens_second = ( + c128a_attn._build_sparse_index_metadata( + kv_cache=torch.empty((1, 2, 512), dtype=torch.bfloat16), + swa_k_cache=torch.empty((1, 64, 512), dtype=torch.bfloat16), + swa_metadata=c128a_metadata, + attn_metadata=c128a_flashmla_md, + swa_only=False, + ) + ) + + assert builder_calls == 2 + assert sparse_indices_first is sparse_indices_second + assert sparse_lens_first is sparse_lens_second + + c4a_attn = make_attn(4, 2) + c4a_metadata = make_swa_metadata() + c4a_flashmla_md = make_flashmla_metadata() + c4a_flashmla_md.c128a_global_decode_topk_indices = None + c4a_flashmla_md.c128a_decode_topk_lens = None + c4a_flashmla_md.c128a_prefill_topk_indices = None + _, _, sparse_indices_third, sparse_lens_third = ( + c4a_attn._build_sparse_index_metadata( + kv_cache=torch.empty((1, 2, 512), dtype=torch.bfloat16), + swa_k_cache=torch.empty((1, 64, 512), dtype=torch.bfloat16), + swa_metadata=c4a_metadata, + attn_metadata=c4a_flashmla_md, + swa_only=False, + ) + ) + _, _, sparse_indices_fourth, sparse_lens_fourth = ( + c4a_attn._build_sparse_index_metadata( + kv_cache=torch.empty((1, 2, 512), dtype=torch.bfloat16), + swa_k_cache=torch.empty((1, 64, 512), dtype=torch.bfloat16), + swa_metadata=c4a_metadata, + attn_metadata=c4a_flashmla_md, + swa_only=False, + ) + ) + + assert builder_calls == 4 + assert sparse_indices_third is not sparse_indices_fourth + assert sparse_lens_third is not sparse_lens_fourth diff --git a/tests/kernels/attention/test_minimax_m3.py b/tests/kernels/attention/test_minimax_m3.py new file mode 100644 index 000000000000..1246f1721c20 --- /dev/null +++ b/tests/kernels/attention/test_minimax_m3.py @@ -0,0 +1,902 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Correctness tests for MiniMax M3 sparse prefill attention kernels.""" + +import pytest +import torch + +from vllm import _custom_ops as ops +from vllm.models.minimax_m3.common.indexer import ( + MiniMaxM3IndexerBackend, +) +from vllm.models.minimax_m3.common.ops.index_topk import ( + minimax_m3_index_decode, + minimax_m3_index_score, + minimax_m3_index_topk, +) +from vllm.models.minimax_m3.common.ops.sparse_attn import ( + _FP8_DTYPES, + minimax_m3_sparse_attn, + minimax_m3_sparse_attn_decode, +) +from vllm.models.minimax_m3.common.sparse_attention import ( + MiniMaxM3SparseBackend, + MiniMaxM3SparseTritonImpl, +) +from vllm.platforms import current_platform +from vllm.v1.attention.backends.utils import set_kv_cache_layout +from vllm.v1.kv_cache_interface import FullAttentionSpec, MLAAttentionSpec +from vllm.v1.worker.gpu.attn_utils import _reshape_kv_cache +from vllm.v1.worker.utils import AttentionGroup + +if not (current_platform.is_cuda() or current_platform.is_rocm()): + pytest.skip( + "MiniMax M3 attention kernels require CUDA or ROCm.", + allow_module_level=True, + ) + + +@pytest.fixture +def kv_layout(request): + """Set the global KV cache layout for one test and restore it after.""" + set_kv_cache_layout(request.param) + try: + yield request.param + finally: + set_kv_cache_layout(None) + + +def _stride_order_for(backend: type[MiniMaxM3SparseBackend], ndim: int) -> tuple: + """Mirror the allocator's stride-order resolution (identity fallback).""" + try: + stride_order = backend.get_kv_cache_stride_order() + assert len(stride_order) == ndim + except (AttributeError, NotImplementedError): + stride_order = tuple(range(ndim)) + return stride_order + + +def _allocate_main_kv_via_contract( + num_pages: int, device: torch.device | str = "cuda" +) -> torch.Tensor: + """Build the main KV cache exactly as the production allocator does for the + currently active layout: allocate the physical (permuted) tensor, then + expose the inverse-permuted logical-NHD view the backend sees.""" + logical_shape = MiniMaxM3SparseBackend.get_kv_cache_shape( + num_pages, BLOCK_SIZE, NUM_KV_HEADS, HEAD_DIM + ) + stride_order = _stride_order_for(MiniMaxM3SparseBackend, len(logical_shape)) + physical_shape = tuple(logical_shape[i] for i in stride_order) + inv_order = [stride_order.index(i) for i in range(len(stride_order))] + raw = torch.randn(physical_shape, device=device, dtype=DTYPE) + return raw.permute(*inv_order) + + +NUM_Q_HEADS = 32 +NUM_KV_HEADS = 2 +HEAD_DIM = 128 +BLOCK_SIZE = 128 +DTYPE = torch.bfloat16 +SM_SCALE = HEAD_DIM**-0.5 +TOPK = 16 + + +@pytest.mark.parametrize( + ("kv_cache_dtype", "expected_dtype"), + [ + ("fp8", current_platform.fp8_dtype()), + ("fp8_e4m3", current_platform.fp8_dtype()), + ( + "fp8_e5m2", + torch.float8_e5m2fnuz + if current_platform.is_fp8_fnuz() + else torch.float8_e5m2, + ), + ], +) +def test_sparse_impl_uses_platform_fp8_dtype( + kv_cache_dtype: str, + expected_dtype: torch.dtype, +): + impl = MiniMaxM3SparseTritonImpl( + num_heads=NUM_Q_HEADS, + head_size=HEAD_DIM, + scale=SM_SCALE, + num_kv_heads=NUM_KV_HEADS, + kv_cache_dtype=kv_cache_dtype, + topk_blocks=TOPK, + sparse_block_size=BLOCK_SIZE, + ) + assert impl.kv_cache_fp8_dtype == expected_dtype + + +@pytest.mark.parametrize( + "dtype", + [ + torch.float8_e4m3fn, + torch.float8_e4m3fnuz, + torch.float8_e5m2, + torch.float8_e5m2fnuz, + ], +) +def test_sparse_kernels_recognize_fp8_dtypes(dtype: torch.dtype): + assert dtype in _FP8_DTYPES + + +# Index top-k kernels. +def _reference_index_topk( + idx_q: torch.Tensor, + index_kv_cache: torch.Tensor, + block_table: torch.Tensor, + q_lens: torch.Tensor, + seq_lens: torch.Tensor, + prefix_lens: torch.Tensor, + topk: int, + init_blocks: int, + local_blocks: int, +) -> torch.Tensor: + total_q, num_idx_heads, _ = idx_q.shape + out = torch.full( + (num_idx_heads, total_q, topk), -1, device=idx_q.device, dtype=torch.int32 + ) + + q_start = 0 + for req_id, (q_len, seq_len, prefix_len) in enumerate( + zip(q_lens.tolist(), seq_lens.tolist(), prefix_lens.tolist()) + ): + q_end = q_start + q_len + q = idx_q[q_start:q_end] + num_blocks = (seq_len + BLOCK_SIZE - 1) // BLOCK_SIZE + pages = block_table[req_id, :num_blocks] + k = index_kv_cache[pages].reshape(num_blocks * BLOCK_SIZE, -1) + score = torch.einsum("qhd,kd->hqk", q.float(), k.float()) + + q_pos = prefix_len + torch.arange(q_len, device=idx_q.device) + k_pos = torch.arange(k.shape[0], device=idx_q.device) + score.masked_fill_(k_pos[None, :] > q_pos[:, None], -float("inf")) + score = score.reshape(num_idx_heads, q_len, num_blocks, BLOCK_SIZE) + score_tensor = score.max(dim=3).values + + valid_blocks = (q_pos + BLOCK_SIZE) // BLOCK_SIZE + for local_q, num_valid_blocks in enumerate(valid_blocks.tolist()): + end = min(init_blocks, num_valid_blocks) + score_tensor[:, local_q, :end] = 1e30 + start = max(0, num_valid_blocks - local_blocks) + score_tensor[:, local_q, start:num_valid_blocks] = 1e29 + + k = min(topk, num_valid_blocks) + topk_idx = score_tensor[:, local_q].topk(k, dim=1).indices + out[:, q_start + local_q, :k] = topk_idx + q_start = q_end + + return out + + +def _assert_topk_indices_equal_unordered( + actual: torch.Tensor, + expected: torch.Tensor, +) -> None: + """Compare selected sparse blocks without requiring a deterministic order.""" + assert actual.shape == expected.shape + actual_flat = actual.cpu().reshape(-1, actual.shape[-1]).tolist() + expected_flat = expected.cpu().reshape(-1, expected.shape[-1]).tolist() + for actual_row, expected_row in zip(actual_flat, expected_flat): + assert set(actual_row) == set(expected_row) + + +def test_prefill_index_topk_correctness(): + topk = 6 + init_blocks = 0 + local_blocks = 1 + num_idx_heads = 2 + head_dim = 16 + q_lens = torch.tensor((4, 3), device="cuda", dtype=torch.int32) + prefix_lens = torch.tensor((0, 1024), device="cuda", dtype=torch.int32) + seq_lens = prefix_lens + q_lens + batch = q_lens.numel() + max_seq_len = seq_lens.max().item() + max_blocks = (max_seq_len + BLOCK_SIZE - 1) // BLOCK_SIZE + num_pages = batch * max_blocks + + cu_seqlens = torch.zeros(batch + 1, device="cuda", dtype=torch.int32) + cu_seqlens[1:] = q_lens.cumsum(0) + block_table = torch.randperm(num_pages, device="cuda", dtype=torch.int32).reshape( + batch, max_blocks + ) + idx_q = torch.ones(q_lens.sum().item(), num_idx_heads, head_dim, device="cuda") + index_kv_cache = torch.empty(num_pages, BLOCK_SIZE, head_dim, device="cuda") + for req_id in range(batch): + for block_id in range(max_blocks): + page = block_table[req_id, block_id] + index_kv_cache[page].fill_(block_id + 1) + + score = minimax_m3_index_score( + idx_q, + index_kv_cache, + block_table, + cu_seqlens, + seq_lens, + prefix_lens, + max_query_len=q_lens.max().item(), + max_seq_len=max_seq_len, + num_kv_heads=num_idx_heads, + ) + actual = minimax_m3_index_topk( + score, + cu_seqlens, + prefix_lens, + max_query_len=q_lens.max().item(), + topk=topk, + init_blocks=init_blocks, + local_blocks=local_blocks, + ) + expected = _reference_index_topk( + idx_q, + index_kv_cache, + block_table, + q_lens, + seq_lens, + prefix_lens, + topk, + init_blocks, + local_blocks, + ) + _assert_topk_indices_equal_unordered(actual, expected) + + +@pytest.mark.parametrize( + ("decode_query_len", "max_decode_query_len"), + [ + (1, 1), + (1, 4), + (4, 4), + ], +) +@pytest.mark.parametrize("num_padded_reqs", [0, 2]) +def test_decode_index_topk_correctness( + decode_query_len: int, + max_decode_query_len: int, + num_padded_reqs: int, +): + topk = 6 + init_blocks = 0 + local_blocks = 1 + num_idx_heads = 2 + head_dim = 16 + active_seq_lens = torch.tensor((7, 129, 1025), device="cuda", dtype=torch.int32) + q_lens = torch.full_like(active_seq_lens, decode_query_len) + prefix_lens = active_seq_lens - decode_query_len + active_batch = active_seq_lens.numel() + batch = active_batch + num_padded_reqs + seq_lens = torch.cat( + [ + active_seq_lens, + torch.zeros(num_padded_reqs, device="cuda", dtype=torch.int32), + ] + ) + max_seq_len = active_seq_lens.max().item() + max_blocks = (max_seq_len + BLOCK_SIZE - 1) // BLOCK_SIZE + num_pages = active_batch * max_blocks + + active_block_table = torch.randperm( + num_pages, device="cuda", dtype=torch.int32 + ).reshape(active_batch, max_blocks) + block_table = torch.zeros(batch, max_blocks, device="cuda", dtype=torch.int32) + block_table[:active_batch] = active_block_table + idx_q = torch.randn( + batch * decode_query_len, num_idx_heads, head_dim, device="cuda" + ) + index_kv_cache = torch.randn(num_pages, BLOCK_SIZE, head_dim, device="cuda") + + actual = minimax_m3_index_decode( + idx_q, + index_kv_cache, + block_table, + seq_lens, + max_seq_len=max_seq_len, + topk=topk, + init_blocks=init_blocks, + local_blocks=local_blocks, + num_kv_heads=num_idx_heads, + decode_query_len=decode_query_len, + max_decode_query_len=max_decode_query_len, + ) + expected = torch.full_like(actual, -1) + active_tokens = active_batch * decode_query_len + expected[:, :active_tokens] = _reference_index_topk( + idx_q[:active_tokens], + index_kv_cache, + block_table[:active_batch], + q_lens, + active_seq_lens, + prefix_lens, + topk, + init_blocks, + local_blocks, + ) + _assert_topk_indices_equal_unordered(actual, expected) + + +# Sparse attention kernels. +def _reference_sparse_attn( + q: torch.Tensor, + kv_cache: torch.Tensor, + topk_idx: torch.Tensor, + block_table: torch.Tensor, + q_lens: torch.Tensor, + seq_lens: torch.Tensor, + prefix_lens: torch.Tensor, +) -> torch.Tensor: + out = torch.empty_like(q, dtype=torch.float32) + gqa_group_size = NUM_Q_HEADS // NUM_KV_HEADS + q_start = 0 + for req_id, (q_len, seq_len, prefix_len) in enumerate( + zip(q_lens.tolist(), seq_lens.tolist(), prefix_lens.tolist()) + ): + q_end = q_start + q_len + q_req = q[q_start:q_end] + positions = torch.arange(seq_len, device="cuda") + pages = block_table[req_id, positions // BLOCK_SIZE] + rows = positions % BLOCK_SIZE + k_req = kv_cache[pages, 0, rows] + v_req = kv_cache[pages, 1, rows].float() + + q_pos = prefix_len + torch.arange(q_len, device="cuda") + key_blocks = positions // BLOCK_SIZE + causal_mask = positions.unsqueeze(0) <= q_pos.unsqueeze(1) + + for kv_head in range(NUM_KV_HEADS): + selected = topk_idx[kv_head, q_start:q_end] + selected_mask = (key_blocks[None, :, None] == selected[:, None, :]).any(-1) + mask = causal_mask & selected_mask + head_start = kv_head * gqa_group_size + head_end = head_start + gqa_group_size + + q_heads = q_req[:, head_start:head_end].transpose(0, 1) + k_head = k_req[:, kv_head].T.expand(gqa_group_size, -1, -1) + scores = torch.bmm(q_heads, k_head, out_dtype=torch.float32) + scores = scores.transpose(0, 1) * SM_SCALE + probs = torch.softmax( + scores.masked_fill(~mask[:, None, :], -float("inf")), -1 + ) + out[q_start:q_end, head_start:head_end] = torch.einsum( + "qhk,kd->qhd", probs, v_req[:, kv_head] + ) + q_start += q_len + return out.to(q.dtype) + + +@pytest.mark.parametrize("kv_layout", ["NHD", "HND"], indirect=True) +@pytest.mark.parametrize( + ("q_lens", "kv_lens"), + [ + ((129, 257), (129, 257)), + ((65, 129, 257), (129, 257, 385)), + ], +) +def test_prefill_sparse_attention_correctness( + kv_layout: str, + q_lens: tuple[int, ...], + kv_lens: tuple[int, ...], +): + assert len(q_lens) == len(kv_lens) + assert all(kv_len >= q_len for q_len, kv_len in zip(q_lens, kv_lens)) + + # Build paged-KV metadata, including a non-identity page order. + batch = len(q_lens) + pages_per_req = [(kv_len + BLOCK_SIZE - 1) // BLOCK_SIZE for kv_len in kv_lens] + max_blocks = max(pages_per_req) + num_pages = sum(pages_per_req) + physical_pages = torch.randperm(num_pages, device="cuda", dtype=torch.int32) + block_table = torch.zeros(batch, max_blocks, device="cuda", dtype=torch.int32) + base_page = 0 + for req_id, num_req_pages in enumerate(pages_per_req): + block_table[req_id, :num_req_pages] = physical_pages[ + base_page : base_page + num_req_pages + ] + base_page += num_req_pages + + q_lens_t = torch.tensor(q_lens, device="cuda", dtype=torch.int32) + seq_lens = torch.tensor(kv_lens, device="cuda", dtype=torch.int32) + prefix_lens = seq_lens - q_lens_t + cu_seqlens = torch.zeros(batch + 1, device="cuda", dtype=torch.int32) + cu_seqlens[1:] = q_lens_t.cumsum(0) + total_q = sum(q_lens) + max_seqlen_q = max(q_lens) + + q_shape = (total_q, NUM_Q_HEADS, HEAD_DIM) + q = torch.randn(q_shape, device="cuda", dtype=DTYPE) + # Allocate the main KV cache through the backend layout contract so the + # physical storage matches the active layout (contiguous NHD or strided + # HND), while the kernels and reference see the logical-NHD view. + kv_cache = _allocate_main_kv_via_contract(num_pages) + + # Build sparse block indices with the same contract as the real M3 indexer: + # one forced local block, then score-selected older causal blocks. + topk_shape = (NUM_KV_HEADS, total_q, TOPK) + topk_idx = torch.full(topk_shape, -1, device="cuda", dtype=torch.int32) + q_start = 0 + for q_len, prefix_len in zip(q_lens_t.tolist(), prefix_lens.tolist()): + for local_q in range(q_len): + current_block = (prefix_len + local_q) // BLOCK_SIZE + older_blocks = torch.randperm( + current_block, device="cuda", dtype=torch.int32 + ) + selected = torch.cat( + [ + torch.tensor([current_block], device="cuda", dtype=torch.int32), + older_blocks[: TOPK - 1], + ] + ) + topk_idx[:, q_start + local_q, : selected.numel()] = selected + q_start += q_len + + actual = torch.empty_like(q) + minimax_m3_sparse_attn( + q, + kv_cache, + topk_idx, + block_table, + cu_seqlens, + seq_lens, + prefix_lens, + max_seqlen_q, + NUM_KV_HEADS, + SM_SCALE, + actual, + ) + + expected = _reference_sparse_attn( + q, + kv_cache, + topk_idx, + block_table, + q_lens_t, + seq_lens, + prefix_lens, + ) + torch.accelerator.synchronize() + + error = (actual.float() - expected.float()).abs() + assert error.mean().item() < 2.5e-4 + assert error.max().item() < 1.7e-2 + + +def test_main_backend_layout_contract(): + """The main sparse backend exposes the logical-NHD shape and the + flash_attn-style stride order for each layout.""" + nb, bs, h, d = 7, BLOCK_SIZE, NUM_KV_HEADS, HEAD_DIM + logical = MiniMaxM3SparseBackend.get_kv_cache_shape(nb, bs, h, d) + assert logical == (nb, 2, bs, h, d) + # The old HND-ordered shape is no longer the logical shape. + assert logical != (nb, 2, h, bs, d) + + try: + set_kv_cache_layout("HND") + assert MiniMaxM3SparseBackend.get_kv_cache_stride_order() == (0, 1, 3, 2, 4) + set_kv_cache_layout("NHD") + assert MiniMaxM3SparseBackend.get_kv_cache_stride_order() == (0, 1, 2, 3, 4) + finally: + set_kv_cache_layout(None) + + for layout in ("NHD", "HND"): + try: + set_kv_cache_layout(layout) + order = MiniMaxM3SparseBackend.get_kv_cache_stride_order() + finally: + set_kv_cache_layout(None) + # Valid permutation: no duplicates, covers every axis. + assert set(order) == set(range(len(order))) + + # M3 has no cross-layer KV blocks. + with pytest.raises(NotImplementedError): + MiniMaxM3SparseBackend.get_kv_cache_stride_order( + include_num_layers_dimension=True + ) + + +def test_main_backend_unknown_layout_raises(monkeypatch): + """An unrecognized layout (injected past env-var validation) is rejected.""" + import vllm.models.minimax_m3.common.sparse_attention as sparse_attn_mod + + monkeypatch.setattr(sparse_attn_mod, "get_kv_cache_layout", lambda: "BOGUS") + with pytest.raises(ValueError, match="Unknown cache layout format"): + MiniMaxM3SparseBackend.get_kv_cache_stride_order() + + +def test_indexer_backend_stride_order_is_identity(): + """The 3-dim indexer cache must not inherit the parent's 5-element stride + order; it overrides to the 3-element identity so the allocator keeps the + contiguous layout.""" + assert MiniMaxM3IndexerBackend.get_kv_cache_stride_order() == (0, 1, 2) + + # Cross-layer (per-layer-stacked) KV blocks are not supported. + with pytest.raises(NotImplementedError): + MiniMaxM3IndexerBackend.get_kv_cache_stride_order( + include_num_layers_dimension=True + ) + + # The stride order matches the 3-dim indexer shape rank. + indexer_shape = MiniMaxM3IndexerBackend.get_kv_cache_shape( + 5, BLOCK_SIZE, 1, HEAD_DIM + ) + assert len(indexer_shape) == 3 + assert _stride_order_for(MiniMaxM3IndexerBackend, len(indexer_shape)) == (0, 1, 2) + + +def test_hnd_allocation_is_byte_identical_to_transpose(): + """Under HND the backend-visible logical view is byte-identical to the + pre-change allocate-HND-then-transpose(2, 3) workaround.""" + nb, bs, h, d = 4, BLOCK_SIZE, NUM_KV_HEADS, HEAD_DIM + logical = MiniMaxM3SparseBackend.get_kv_cache_shape(nb, bs, h, d) + try: + set_kv_cache_layout("HND") + stride_order = MiniMaxM3SparseBackend.get_kv_cache_stride_order() + finally: + set_kv_cache_layout(None) + + physical_shape = tuple(logical[i] for i in stride_order) + # The physical (permuted) shape equals the old hardcoded HND shape. + assert physical_shape == (nb, 2, h, bs, d) + + inv_order = [stride_order.index(i) for i in range(len(stride_order))] + raw = torch.empty(physical_shape, device="cuda", dtype=DTYPE) + view = raw.permute(*inv_order) + expected = raw.view((nb, 2, h, bs, d)).transpose(2, 3) + + assert view.shape == expected.shape + assert view.stride() == expected.stride() + assert view.storage_offset() == expected.storage_offset() + + # Negative: the identity (wrong) stride order under HND does not reproduce + # the transpose view. + wrong_view = raw.view(logical) + assert wrong_view.stride() != expected.stride() + + +def test_main_cache_is_block_first_and_unpadded(): + """The allocator's contiguous-view branch (not the padded-strided branch) + is used for the main GQA cache: its spec is unpadded and the physical + layout keeps num_blocks as the first dimension under both layouts.""" + from vllm.v1.kv_cache_interface import FullAttentionSpec + + spec = FullAttentionSpec( + block_size=BLOCK_SIZE, + num_kv_heads=NUM_KV_HEADS, + head_size=HEAD_DIM, + head_size_v=HEAD_DIM, + dtype=DTYPE, + ) + # Unpadded -> allocator uses kv_tensor.view(...) rather than as_strided(). + assert spec.page_size_padded is None + + logical = MiniMaxM3SparseBackend.get_kv_cache_shape( + 4, BLOCK_SIZE, NUM_KV_HEADS, HEAD_DIM + ) + for layout in ("NHD", "HND"): + try: + set_kv_cache_layout(layout) + order = MiniMaxM3SparseBackend.get_kv_cache_stride_order() + finally: + set_kv_cache_layout(None) + inv_order = [order.index(i) for i in range(len(order))] + # Physical first dim is num_blocks (block-first); required by the + # padded-strided branch's block-first assumption if it were ever taken. + assert inv_order[0] == 0 + assert logical[order[0]] == logical[0] + + +def _build_decode_inputs( + seq_lens_list: tuple[int, ...], + decode_query_len: int = 1, + num_padded_reqs: int = 0, +): + """Shared decode setup: uniform query tokens per request, a non-identity + block table, and topk indices selecting the current block plus older causal + blocks for each query token.""" + active_batch = len(seq_lens_list) + batch = active_batch + num_padded_reqs + pages_per_req = [(s + BLOCK_SIZE - 1) // BLOCK_SIZE for s in seq_lens_list] + max_blocks = max(pages_per_req) + num_pages = sum(pages_per_req) + physical_pages = torch.randperm(num_pages, device="cuda", dtype=torch.int32) + block_table = torch.zeros(batch, max_blocks, device="cuda", dtype=torch.int32) + base_page = 0 + for req_id, num_req_pages in enumerate(pages_per_req): + block_table[req_id, :num_req_pages] = physical_pages[ + base_page : base_page + num_req_pages + ] + base_page += num_req_pages + + seq_lens = torch.tensor( + (*seq_lens_list, *([0] * num_padded_reqs)), + device="cuda", + dtype=torch.int32, + ) + q = torch.randn( + batch * decode_query_len, NUM_Q_HEADS, HEAD_DIM, device="cuda", dtype=DTYPE + ) + + topk_idx = torch.full( + (NUM_KV_HEADS, batch * decode_query_len, TOPK), + -1, + device="cuda", + dtype=torch.int32, + ) + token_id = 0 + for req_id, seq_len in enumerate(seq_lens_list): + for local_q in range(decode_query_len): + query_pos = seq_len - decode_query_len + local_q + current_block = query_pos // BLOCK_SIZE + older_blocks = torch.randperm( + current_block, device="cuda", dtype=torch.int32 + ) + selected = torch.cat( + [ + torch.tensor([current_block], device="cuda", dtype=torch.int32), + older_blocks[: TOPK - 1], + ] + ) + topk_idx[:, token_id, : selected.numel()] = selected + token_id += 1 + + return q, block_table, seq_lens, topk_idx, num_pages + + +@pytest.mark.parametrize("kv_layout", ["NHD", "HND"], indirect=True) +@pytest.mark.parametrize( + "seq_lens_list", + [(130, 257), (129, 200, 384)], +) +@pytest.mark.parametrize("decode_query_len", [1, 4]) +@pytest.mark.parametrize("num_padded_reqs", [0, 2]) +def test_decode_sparse_attention_correctness( + kv_layout: str, + seq_lens_list: tuple[int, ...], + decode_query_len: int, + num_padded_reqs: int, +): + """Decode (split-K) parity under both layouts: this is the only coverage of + the decode-site cache feed, and the strided HND case fails if the kernel + ignores the cache strides.""" + torch.manual_seed(0) + q, block_table, seq_lens, topk_idx, num_pages = _build_decode_inputs( + seq_lens_list, decode_query_len, num_padded_reqs + ) + kv_cache = _allocate_main_kv_via_contract(num_pages) + + actual = torch.empty_like(q) + minimax_m3_sparse_attn_decode( + q, + kv_cache, + topk_idx, + block_table, + seq_lens, + NUM_KV_HEADS, + SM_SCALE, + actual, + decode_query_len, + ) + + # Reuse the prefill reference: decode is a uniform query chunk ending at + # seq_len - 1 for each request. + active_batch = len(seq_lens_list) + active_tokens = active_batch * decode_query_len + q_lens_t = torch.full( + (len(seq_lens_list),), decode_query_len, device="cuda", dtype=torch.int32 + ) + active_seq_lens = seq_lens[:active_batch] + prefix_lens = active_seq_lens - q_lens_t + expected = _reference_sparse_attn( + q[:active_tokens], + kv_cache, + topk_idx[:, :active_tokens], + block_table[:active_batch], + q_lens_t, + active_seq_lens, + prefix_lens, + ) + torch.accelerator.synchronize() + + error = (actual[:active_tokens].float() - expected.float()).abs() + assert error.mean().item() < 2.5e-4 + assert error.max().item() < 1.7e-2 + + +def test_decode_wrong_layout_breaks_parity(): + """Negative (AC-3/AC-5): consuming the physical HND buffer as if it were + already contiguous-NHD (i.e. skipping the allocator's inverse permute) + reorders the K/V content, so the decode output no longer matches the + reference computed on the correct logical view. The mislabeled tensor keeps + the same shape as the correct view, so the kernel stays in bounds.""" + torch.manual_seed(0) + seq_lens_list = (130, 257) + q, block_table, seq_lens, topk_idx, num_pages = _build_decode_inputs(seq_lens_list) + + # Physical HND storage [blocks, 2, heads, block, dim]. + phys = torch.randn( + (num_pages, 2, NUM_KV_HEADS, BLOCK_SIZE, HEAD_DIM), device="cuda", dtype=DTYPE + ) + # Correct logical-NHD view (strided) vs. the same bytes mislabeled as a + # contiguous-NHD cache — same shape, different content mapping. + correct = phys.permute(0, 1, 3, 2, 4) + wrong = phys.reshape(num_pages, 2, BLOCK_SIZE, NUM_KV_HEADS, HEAD_DIM) + + q_lens_t = torch.ones(len(seq_lens_list), device="cuda", dtype=torch.int32) + prefix_lens = seq_lens - q_lens_t + expected = _reference_sparse_attn( + q, correct, topk_idx, block_table, q_lens_t, seq_lens, prefix_lens + ) + + actual = torch.empty_like(q) + minimax_m3_sparse_attn_decode( + q, wrong, topk_idx, block_table, seq_lens, NUM_KV_HEADS, SM_SCALE, actual, 1 + ) + torch.accelerator.synchronize() + assert (actual.float() - expected.float()).abs().max().item() > 1.7e-2 + + +def _make_attn_group(backend, spec): + return AttentionGroup( + backend=backend, + layer_names=["main"], + kv_cache_spec=spec, + kv_cache_group_id=0, + ) + + +def test_main_cache_byte_identical_through_production_allocator(): + """AC-2: drive the real allocator (`_reshape_kv_cache`) for the M3 main + `FullAttentionSpec` under HND and assert the backend-visible view has the + same shape, stride, and storage offset as the pre-change + allocate-HND-then-transpose path; the indexer `MLAAttentionSpec` allocates + through the same path to its 3-dim shape.""" + nb = 4 + spec = FullAttentionSpec( + block_size=BLOCK_SIZE, + num_kv_heads=NUM_KV_HEADS, + head_size=HEAD_DIM, + head_size_v=HEAD_DIM, + dtype=DTYPE, + ) + raw = torch.zeros(nb * spec.page_size_bytes, dtype=torch.int8) + group = _make_attn_group(MiniMaxM3SparseBackend, spec) + try: + set_kv_cache_layout("HND") + kv_caches = _reshape_kv_cache([group], {"main": raw}, "auto", [BLOCK_SIZE], {}) + finally: + set_kv_cache_layout(None) + view = kv_caches["main"] + + oracle = raw.view(DTYPE).view((nb, 2, NUM_KV_HEADS, BLOCK_SIZE, HEAD_DIM)) + oracle = oracle.transpose(2, 3) + assert tuple(view.shape) == tuple(oracle.shape) + assert view.stride() == oracle.stride() + assert view.storage_offset() == oracle.storage_offset() + + # Indexer cache allocates through the same path under both layouts. + ispec = MLAAttentionSpec( + block_size=BLOCK_SIZE, num_kv_heads=1, head_size=HEAD_DIM, dtype=DTYPE + ) + for layout in ("NHD", "HND"): + iraw = torch.zeros(nb * ispec.page_size_bytes, dtype=torch.int8) + igroup = AttentionGroup( + backend=MiniMaxM3IndexerBackend, + layer_names=["idx"], + kv_cache_spec=ispec, + kv_cache_group_id=0, + ) + try: + set_kv_cache_layout(layout) + iout = _reshape_kv_cache([igroup], {"idx": iraw}, "auto", [BLOCK_SIZE], {}) + finally: + set_kv_cache_layout(None) + assert tuple(iout["idx"].shape) == (nb, BLOCK_SIZE, HEAD_DIM) + + +def test_indexer_inherited_stride_order_trips_allocator_assert(): + """AC-4 negative: without the indexer override, the inherited 5-element + stride order trips the allocator's `len(stride_order) == len(shape)` assert + for the 3-dim indexer shape; the `AssertionError` is NOT swallowed by the + allocator's `(AttributeError, NotImplementedError)` fallback.""" + + class _BrokenIndexerBackend(MiniMaxM3IndexerBackend): + # Simulate inheriting the parent's 5-element stride order. + get_kv_cache_stride_order = staticmethod( + MiniMaxM3SparseBackend.get_kv_cache_stride_order + ) + + nb = 4 + ispec = MLAAttentionSpec( + block_size=BLOCK_SIZE, num_kv_heads=1, head_size=HEAD_DIM, dtype=DTYPE + ) + iraw = torch.zeros(nb * ispec.page_size_bytes, dtype=torch.int8) + igroup = AttentionGroup( + backend=_BrokenIndexerBackend, + layer_names=["idx"], + kv_cache_spec=ispec, + kv_cache_group_id=0, + ) + try: + set_kv_cache_layout("HND") + with pytest.raises(AssertionError): + _reshape_kv_cache([igroup], {"idx": iraw}, "auto", [BLOCK_SIZE], {}) + finally: + set_kv_cache_layout(None) + + +def test_padded_main_cache_is_flagged(): + """AC-2.1 negative: the M3 main cache relies on the allocator's + contiguous-view branch (`page_size_padded is None`). A spec that sets + `page_size_padded` is explicitly flagged rather than silently wrong-strided.""" + + def _require_unpadded_block_first(spec, stride_order): + inv_order = [stride_order.index(i) for i in range(len(stride_order))] + assert spec.page_size_padded is None, ( + "main GQA cache must be unpadded to use the contiguous-view " + "allocator branch" + ) + assert inv_order[0] == 0, "main GQA cache must remain block-first" + + try: + set_kv_cache_layout("HND") + stride_order = MiniMaxM3SparseBackend.get_kv_cache_stride_order() + finally: + set_kv_cache_layout(None) + + good = FullAttentionSpec( + block_size=BLOCK_SIZE, + num_kv_heads=NUM_KV_HEADS, + head_size=HEAD_DIM, + head_size_v=HEAD_DIM, + dtype=DTYPE, + ) + _require_unpadded_block_first(good, stride_order) # passes + + padded = FullAttentionSpec( + block_size=BLOCK_SIZE, + num_kv_heads=NUM_KV_HEADS, + head_size=HEAD_DIM, + head_size_v=HEAD_DIM, + dtype=DTYPE, + page_size_padded=good.page_size_bytes + 128, + ) + with pytest.raises(AssertionError): + _require_unpadded_block_first(padded, stride_order) + + +@pytest.mark.parametrize("kv_layout", ["NHD", "HND"], indirect=True) +def test_reshape_and_cache_flash_write_persists(kv_layout: str): + """AC-5 write path: the `reshape_and_cache_flash` write site now consumes + `self.kv_cache.unbind(1)` directly. Writing through those views must persist + into the bound storage (read back through an independent logical view) under + both layouts — a `.contiguous()` copy of the unbind slice would leave the + bound storage unchanged.""" + torch.manual_seed(0) + num_pages = 4 + kv_cache = _allocate_main_kv_via_contract(num_pages) + with torch.no_grad(): + kv_cache.zero_() + + # Exactly the production write-site code under test. + key_cache, value_cache = kv_cache.unbind(1) + + num_tokens = 12 + slot_mapping = torch.randperm(num_pages * BLOCK_SIZE, device="cuda")[ + :num_tokens + ].to(torch.int64) + key = torch.randn(num_tokens, NUM_KV_HEADS, HEAD_DIM, device="cuda", dtype=DTYPE) + value = torch.randn(num_tokens, NUM_KV_HEADS, HEAD_DIM, device="cuda", dtype=DTYPE) + scale = torch.ones((), device="cuda") + ops.reshape_and_cache_flash( + key, value, key_cache, value_cache, slot_mapping, "auto", scale, scale + ) + torch.accelerator.synchronize() + + # Read back through the independent logical view; proves the writes landed + # in the engine-bound storage, not a detached copy. + for t in range(num_tokens): + slot = int(slot_mapping[t].item()) + blk, intra = divmod(slot, BLOCK_SIZE) + torch.testing.assert_close(kv_cache[blk, 0, intra], key[t]) + torch.testing.assert_close(kv_cache[blk, 1, intra], value[t]) diff --git a/tests/kernels/attention/test_rocm_triton_attn_dsv4.py b/tests/kernels/attention/test_rocm_triton_attn_dsv4.py index f328f339332e..daf73b82e614 100644 --- a/tests/kernels/attention/test_rocm_triton_attn_dsv4.py +++ b/tests/kernels/attention/test_rocm_triton_attn_dsv4.py @@ -515,3 +515,218 @@ def test_sparse_attn_decode_split_k_kernel( ) torch.testing.assert_close(actual, expected, atol=2e-2, rtol=2e-2) + + +# --------------------------------------------------------------------------- +# o-projection: fused inverse-RoPE + cached bf16 wo_a (rocm_inv_rope_einsum) +# --------------------------------------------------------------------------- + + +# Cache rows = max_position_embeddings * scaling_factor. +_ROTARY_MAX_POS = 1024 +_ROTARY_SCALING_FACTOR = 4.0 +_ROTARY_CACHE_LEN = int(_ROTARY_MAX_POS * _ROTARY_SCALING_FACTOR) + + +def _make_dsv4_rotary(device: torch.device): + """The official DSv4 rotary embedding, sized down for unit tests.""" + from vllm.model_executor.layers.rotary_embedding.deepseek_scaling_rope import ( + DeepseekV4ScalingRotaryEmbedding, + ) + + # The model loader constructs layers under a default-device context; + # mirror that so the fp32 cos_sin_cache lands on the GPU. + with torch.device(device): + rotary_emb = DeepseekV4ScalingRotaryEmbedding( + head_size=ROPE_HEAD_DIM, + rotary_dim=ROPE_HEAD_DIM, + max_position_embeddings=_ROTARY_MAX_POS, + base=10000, + is_neox_style=False, + scaling_factor=_ROTARY_SCALING_FACTOR, + dtype=torch.bfloat16, + mscale=1.0, + mscale_all_dim=1.0, + ) + rotary_emb = rotary_emb.to(device) + assert rotary_emb.cos_sin_cache.shape == (_ROTARY_CACHE_LEN, ROPE_HEAD_DIM) + return rotary_emb + + +def _inv_rope_via_rotary_native( + rotary_emb: torch.nn.Module, + o: torch.Tensor, + positions: torch.Tensor, +) -> torch.Tensor: + """Reference: the official ``forward_native(inverse=True)`` path.""" + expected, _ = rotary_emb.forward_native(positions, o.clone(), None, inverse=True) + return expected.to(torch.bfloat16) + + +class _FakeWoA(torch.nn.Module): + """Stand-in for the wo_a linear layer holding the (optionally fp8) weight.""" + + def __init__( + self, weight: torch.Tensor, weight_scale_inv: torch.Tensor | None = None + ) -> None: + super().__init__() + self.weight = weight + if weight_scale_inv is not None: + self.weight_scale_inv = weight_scale_inv + + +@pytest.mark.parametrize("num_tokens", [1, 7, 64]) +@pytest.mark.parametrize("num_heads", [1, 8]) +@pytest.mark.parametrize("pos_dtype", [torch.int32, torch.int64]) +@torch.inference_mode() +def test_fused_inverse_rope_gptj_matches_rotary_native( + num_tokens: int, num_heads: int, pos_dtype: torch.dtype, default_vllm_config +) -> None: + from vllm.v1.attention.ops.rocm_aiter_mla_sparse import _fused_inverse_rope_gptj + + device = torch.device("cuda") + torch.manual_seed(0) + rotary_emb = _make_dsv4_rotary(device) + o = torch.randn( + num_tokens, num_heads, HEAD_DIM, dtype=torch.bfloat16, device=device + ) + positions = torch.randint( + 0, _ROTARY_CACHE_LEN, (num_tokens,), dtype=pos_dtype, device=device + ) + + actual = _fused_inverse_rope_gptj( + o, positions, rotary_emb.cos_sin_cache, ROPE_HEAD_DIM + ) + expected = _inv_rope_via_rotary_native(rotary_emb, o, positions) + + assert actual.dtype == torch.bfloat16 + assert actual.shape == o.shape + # NoPE lanes are a pure bf16 passthrough -> must be bit-exact. + assert torch.equal(actual[..., :NOPE_HEAD_DIM], expected[..., :NOPE_HEAD_DIM]) + # RoPE lanes: tolerate at most ~1 bf16 ulp from fp32 fma ordering. + torch.testing.assert_close(actual, expected, atol=2e-2, rtol=2e-2) + + +@torch.inference_mode() +def test_fused_inverse_rope_gptj_empty(default_vllm_config) -> None: + from vllm.v1.attention.ops.rocm_aiter_mla_sparse import _fused_inverse_rope_gptj + + device = torch.device("cuda") + rotary_emb = _make_dsv4_rotary(device) + o = torch.empty(0, 8, HEAD_DIM, dtype=torch.bfloat16, device=device) + positions = torch.empty(0, dtype=torch.int32, device=device) + + out = _fused_inverse_rope_gptj( + o, positions, rotary_emb.cos_sin_cache, ROPE_HEAD_DIM + ) + assert out.shape == (0, 8, HEAD_DIM) + assert out.dtype == torch.bfloat16 + + +@torch.inference_mode() +def test_rocm_inv_rope_einsum_matches_rotary_native(default_vllm_config) -> None: + from vllm.v1.attention.ops.rocm_aiter_mla_sparse import rocm_inv_rope_einsum + + device = torch.device("cuda") + torch.manual_seed(2) + num_tokens, num_heads = 5, 8 + n_local_groups = num_heads + o_lora_rank = 16 + hidden_dim = num_heads * HEAD_DIM // n_local_groups # 512 + + rotary_emb = _make_dsv4_rotary(device) + o = ( + torch.randn( + num_tokens, num_heads, HEAD_DIM, dtype=torch.bfloat16, device=device + ) + * 0.125 + ) + positions = torch.randint( + 0, _ROTARY_CACHE_LEN, (num_tokens,), dtype=torch.int32, device=device + ) + weight = ( + torch.randn(n_local_groups * o_lora_rank, hidden_dim, device=device) * 0.125 + ).to(torch.bfloat16) + wo_a = _FakeWoA(weight) + + actual = rocm_inv_rope_einsum( + rotary_emb, o, positions, ROPE_HEAD_DIM, n_local_groups, o_lora_rank, wo_a + ) + + o_ref = _inv_rope_via_rotary_native(rotary_emb, o, positions) + o_ref = o_ref.view(num_tokens, n_local_groups, -1) + wo_a_ref = weight.view(n_local_groups, o_lora_rank, hidden_dim).to(torch.bfloat16) + expected = torch.einsum("tgd,grd->tgr", o_ref, wo_a_ref) + + assert actual.shape == (num_tokens, n_local_groups, o_lora_rank) + torch.testing.assert_close(actual, expected, atol=2e-2, rtol=2e-2) + + +@torch.inference_mode() +def test_get_cached_wo_a_bf16_plain_caches() -> None: + from vllm.v1.attention.ops.rocm_aiter_mla_sparse import _get_cached_wo_a_bf16 + + device = torch.device("cuda") + torch.manual_seed(4) + n_local_groups, o_lora_rank, hidden_dim = 2, 4, 8 + weight = torch.randn( + n_local_groups * o_lora_rank, hidden_dim, dtype=torch.bfloat16, device=device + ) + wo_a = _FakeWoA(weight) + + out1 = _get_cached_wo_a_bf16(wo_a, n_local_groups, o_lora_rank, hidden_dim) + expected = weight.view(n_local_groups, o_lora_rank, hidden_dim).to(torch.bfloat16) + assert out1.shape == (n_local_groups, o_lora_rank, hidden_dim) + torch.testing.assert_close(out1, expected, atol=0, rtol=0) + assert hasattr(wo_a, "_dsv4_wo_a_bf16") + + # Mutate the source weight: the cached tensor must be returned unchanged + # (proving the dequant is not recomputed per call). + wo_a.weight.zero_() + out2 = _get_cached_wo_a_bf16(wo_a, n_local_groups, o_lora_rank, hidden_dim) + assert out2 is out1 + torch.testing.assert_close(out2, expected, atol=0, rtol=0) + + +@torch.inference_mode() +def test_get_cached_wo_a_bf16_fp8_blockscale_caches() -> None: + from vllm.v1.attention.ops.rocm_aiter_mla_sparse import _get_cached_wo_a_bf16 + + device = torch.device("cuda") + torch.manual_seed(5) + n_local_groups, o_lora_rank, hidden_dim = 2, 4, 8 + row_block, col_block = 2, 2 + row_blocks = o_lora_rank // row_block + col_blocks = hidden_dim // col_block + + fp8_dtype = current_platform.fp8_dtype() + weight_f32 = ( + torch.randn( + n_local_groups, o_lora_rank, hidden_dim, dtype=torch.float32, device=device + ) + * 0.1 + ) + weight_fp8 = weight_f32.to(fp8_dtype) + scale = ( + torch.rand( + n_local_groups, row_blocks, col_blocks, dtype=torch.float32, device=device + ) + * 0.5 + + 0.5 + ) + wo_a = _FakeWoA( + weight_fp8.reshape(n_local_groups * o_lora_rank, hidden_dim), + weight_scale_inv=scale.reshape(n_local_groups * row_blocks, col_blocks), + ) + + out = _get_cached_wo_a_bf16(wo_a, n_local_groups, o_lora_rank, hidden_dim) + + scale_full = scale.repeat_interleave(row_block, dim=-2).repeat_interleave( + col_block, dim=-1 + ) + expected = (weight_fp8.to(torch.float32) * scale_full).to(torch.bfloat16) + assert out.shape == (n_local_groups, o_lora_rank, hidden_dim) + torch.testing.assert_close(out, expected, atol=0, rtol=0) + + # Second call returns the same cached object. + assert _get_cached_wo_a_bf16(wo_a, n_local_groups, o_lora_rank, hidden_dim) is out diff --git a/tests/kernels/core/test_fused_allreduce_gemma_rms_norm.py b/tests/kernels/core/test_fused_allreduce_gemma_rms_norm.py new file mode 100644 index 000000000000..cb936ce33ad1 --- /dev/null +++ b/tests/kernels/core/test_fused_allreduce_gemma_rms_norm.py @@ -0,0 +1,109 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Tests for the manual AllReduce + GemmaRMSNorm fusion used by MiniMax M3. + +``fused_allreduce_gemma_rms_norm`` must match the unfused model path, i.e. +``GemmaRMSNorm(all_reduce(partial), residual)``, both on the flashinfer fast +path (TP>1 with flashinfer + NVSwitch) and on the eager fallback (TP==1, or when +flashinfer is unavailable / the GPU has no NVSwitch). +""" + +import pytest +import torch +from torch.multiprocessing import spawn + +from tests.utils import ensure_current_vllm_config, init_test_distributed_environment +from vllm.distributed import cleanup_dist_env_and_memory +from vllm.distributed.communication_op import tensor_model_parallel_all_reduce +from vllm.model_executor.layers.fused_allreduce_gemma_rms_norm import ( + fused_allreduce_gemma_rms_norm, +) +from vllm.model_executor.layers.layernorm import GemmaRMSNorm +from vllm.platforms import current_platform +from vllm.utils.network_utils import get_open_port +from vllm.utils.torch_utils import set_random_seed + + +@ensure_current_vllm_config() +def _worker_fused_ar_norm( + local_rank, + world_size, + port, + num_tokens, + hidden_size, + dtype, + seed, + eps, +): + """Per-rank worker: compare the fused helper vs all_reduce + GemmaRMSNorm.""" + device = torch.device(f"cuda:{local_rank}") + torch.accelerator.set_device_index(device) + init_test_distributed_environment( + world_size, 1, local_rank, port, local_rank=local_rank + ) + + # Norm weights are identical across ranks (replicated GemmaRMSNorm). + set_random_seed(seed) + norm = GemmaRMSNorm(hidden_size, eps=eps).cuda().to(dtype) + with torch.no_grad(): + norm.weight.normal_(mean=0.0, std=0.1) + + # Residual is shared across ranks; the partial o_proj output differs per rank + # (each rank holds a partial sum that all_reduce combines). + torch.manual_seed(seed + 7) + residual = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) + torch.manual_seed(seed + 1000 + local_rank) + partial = torch.randn(num_tokens, hidden_size, dtype=dtype, device=device) + + # Reference: the unfused model path. + reduced = tensor_model_parallel_all_reduce(partial.clone()) + ref_out, ref_res = norm(reduced, residual.clone()) + + # Fused helper (flashinfer fast path when available, else fallback). + out, res = fused_allreduce_gemma_rms_norm(partial.clone(), residual.clone(), norm) + torch.accelerator.synchronize() + + torch.testing.assert_close(out, ref_out, atol=2e-2, rtol=2e-2) + torch.testing.assert_close(res, ref_res, atol=2e-2, rtol=2e-2) + + cleanup_dist_env_and_memory() + + +@pytest.mark.skipif( + not current_platform.is_cuda(), + reason="CUDA required", +) +# world_size=1 exercises the TP==1 identity branch on a single GPU; >1 exercises +# the all_reduce + GemmaRMSNorm equivalence (flashinfer kernel or fallback). +@pytest.mark.parametrize("world_size", [1, 2, 4]) +@pytest.mark.parametrize("num_tokens", [1, 128, 333]) +@pytest.mark.parametrize("hidden_size", [2048, 4096]) +@pytest.mark.parametrize("dtype", [torch.bfloat16]) +@pytest.mark.parametrize("eps", [1e-6]) +@pytest.mark.parametrize("seed", [42]) +def test_fused_allreduce_gemma_rms_norm( + world_size, + num_tokens, + hidden_size, + dtype, + eps, + seed, +): + num_gpus = current_platform.device_count() + if num_gpus < world_size: + pytest.skip(f"Need >= {world_size} GPUs, have {num_gpus}") + port = str(get_open_port()) + spawn( + _worker_fused_ar_norm, + args=( + world_size, + port, + num_tokens, + hidden_size, + dtype, + seed, + eps, + ), + nprocs=world_size, + join=True, + ) diff --git a/tests/kernels/core/test_layernorm.py b/tests/kernels/core/test_layernorm.py index c39d42c75930..fde09710b5db 100644 --- a/tests/kernels/core/test_layernorm.py +++ b/tests/kernels/core/test_layernorm.py @@ -6,6 +6,7 @@ from tests.kernels.quant_utils import FP8_DTYPE from tests.kernels.utils import opcheck +from vllm import ir from vllm.model_executor.layers.layernorm import GemmaRMSNorm, RMSNorm from vllm.platforms import current_platform from vllm.utils.torch_utils import set_random_seed @@ -27,6 +28,10 @@ ] +def _rms_norm_tolerance(dtype: torch.dtype) -> dict[str, float]: + return ir.ops.rms_norm.get_tolerance(dtype) + + @pytest.mark.parametrize("num_tokens", NUM_TOKENS) @pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) @pytest.mark.parametrize("add_residual", ADD_RESIDUAL) @@ -81,6 +86,49 @@ def test_rms_norm( ) +@pytest.mark.parametrize("num_tokens", NUM_TOKENS) +@pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) +@pytest.mark.parametrize("add_residual", ADD_RESIDUAL) +@pytest.mark.parametrize("dtype", DTYPES) +@pytest.mark.parametrize("seed", SEEDS) +@pytest.mark.parametrize("device", CUDA_DEVICES) +@torch.inference_mode() +def test_rms_norm_weightless( + default_vllm_config, + num_tokens: int, + hidden_size: int, + add_residual: bool, + dtype: torch.dtype, + seed: int, + device: str, +) -> None: + set_random_seed(seed) + torch.set_default_device(device) + layer = RMSNorm(hidden_size, has_weight=False).to(dtype=dtype) + x = torch.randn(num_tokens, hidden_size, dtype=dtype) + residual = torch.randn_like(x) if add_residual else None + + ref_out = layer.forward_native(x, residual) + out = layer(x, residual) + tol = _rms_norm_tolerance(dtype) + if add_residual: + torch.testing.assert_close(out[0], ref_out[0], **tol) + torch.testing.assert_close(out[1], ref_out[1], **tol) + else: + torch.testing.assert_close(out, ref_out, **tol) + + if residual is not None: + opcheck( + torch.ops._C.fused_add_rms_norm, + (x, residual, None, layer.variance_epsilon), + ) + else: + opcheck( + torch.ops._C.rms_norm, + (out, x, None, layer.variance_epsilon), + ) + + @pytest.mark.parametrize("num_tokens", NUM_TOKENS) @pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) @pytest.mark.parametrize("add_residual", ADD_RESIDUAL) diff --git a/tests/kernels/helion/test_dynamic_per_token_scaled_fp8_quant.py b/tests/kernels/helion/test_dynamic_per_token_scaled_fp8_quant.py new file mode 100644 index 000000000000..50fd9b70d256 --- /dev/null +++ b/tests/kernels/helion/test_dynamic_per_token_scaled_fp8_quant.py @@ -0,0 +1,165 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Tests for the dynamic_per_token_scaled_fp8_quant helion kernel + +Run `pytest tests/kernels/helion/test_dynamic_per_token_scaled_fp8_quant.py`. +""" + +from typing import Any + +import pytest +import torch +from torch._subclasses.fake_tensor import FakeTensorMode + +from tests.kernels.helion.utils import skip_if_platform_unsupported +from tests.kernels.quant_utils import FP8_DTYPE +from vllm.kernels.helion.case_key import CaseKey +from vllm.kernels.helion.config_manager import ConfigManager +from vllm.kernels.helion.ops.dynamic_per_token_scaled_fp8_quant import ( + _pick_cache, + baseline, + dynamic_per_token_scaled_fp8_quant, + pick_config, +) +from vllm.platforms import current_platform +from vllm.utils.import_utils import has_helion +from vllm.utils.torch_utils import set_random_seed + +if not has_helion(): + pytest.skip( + "Helion is not installed. Install with: pip install vllm[helion]", + allow_module_level=True, + ) + + +def _generate_fake_input(num_tokens: int, hidden_size: int) -> tuple[Any, ...]: + with FakeTensorMode(): + input = torch.randn( + num_tokens, hidden_size, device="cuda", dtype=torch.bfloat16 + ) + result = torch.empty( + input.shape, device=input.device, dtype=current_platform.fp8_dtype() + ) + scale = torch.empty((num_tokens, 1), device=input.device, dtype=torch.float32) + scale_ub = torch.mean(input).to(torch.float32) + args = (result, input, scale, scale_ub) + return args + + +@pytest.fixture(autouse=True) +def reset_config_manager_singleton(): + ConfigManager.reset_instance() + ConfigManager() + yield + ConfigManager.reset_instance() + + +class TestDynamicPerTokenScaledFp8QuantConfigPicker: + def setup_method(self): + _pick_cache.clear() + + def test_config_picker_exact_match(self): + config_keys = [ + CaseKey({"hidden_size": 2048, "num_tokens": 16}), + CaseKey({"hidden_size": 4096, "num_tokens": 16}), + ] + + args = _generate_fake_input(16, 4096) + selected_key = pick_config(args, config_keys) + assert selected_key == CaseKey({"hidden_size": 4096, "num_tokens": 16}) + + def test_config_picker_closest_match(self): + config_keys = [ + CaseKey({"hidden_size": 2048, "num_tokens": 16}), + CaseKey({"hidden_size": 2048, "num_tokens": 32}), + CaseKey({"hidden_size": 4096, "num_tokens": 16}), + CaseKey({"hidden_size": 4096, "num_tokens": 32}), + ] + + args = _generate_fake_input(20, 3000) + selected_key = pick_config(args, config_keys) + assert selected_key == CaseKey({"hidden_size": 2048, "num_tokens": 32}) + + def test_config_picker_no_configs(self): + config_keys: list[dict] = [] + + args = _generate_fake_input(16, 4096) + selected_key = pick_config(args, config_keys) + assert selected_key is None + + def test_config_picker_fallback_to_largest(self): + config_keys = [ + CaseKey({"hidden_size": 2048, "num_tokens": 16}), + CaseKey({"hidden_size": 4096, "num_tokens": 16}), + ] + + args = _generate_fake_input(32, 8192) + selected_key = pick_config(args, config_keys) + assert selected_key == CaseKey({"hidden_size": 4096, "num_tokens": 16}) + + +class TestDynamicPerTokenScaledFp8QuantCorrectness: + @pytest.mark.parametrize("num_tokens", [1, 7, 4096]) + @pytest.mark.parametrize("hidden_size", [17, 1024, 1025, 1026, 5137, 8193]) + @pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float]) + @pytest.mark.parametrize("has_scale_ub", [True, False]) + @pytest.mark.parametrize("seed", [0]) + def test_dynamic_per_token_fp8_quant( + self, + num_tokens: int, + hidden_size: int, + dtype: torch.dtype, + has_scale_ub: bool, + seed: int, + ) -> None: + skip_if_platform_unsupported("dynamic_per_token_scaled_fp8_quant") + set_random_seed(seed) + + x = ( + torch.rand(num_tokens, hidden_size, dtype=dtype, device="cuda") + 1e-6 + ) # avoid nans + + scale_ub = ( + torch.mean(x).to(dtype=torch.float32, device="cuda") + if has_scale_ub + else None + ) + + ref_out = torch.empty(x.shape, device="cuda", dtype=FP8_DTYPE) + ref_scales = torch.empty((x.shape[0], 1), device="cuda", dtype=torch.float32) + baseline(ref_out, x, ref_scales, scale_ub) + + ops_out = torch.empty(x.shape, device="cuda", dtype=FP8_DTYPE) + ops_scales = torch.empty((x.shape[0], 1), device="cuda", dtype=torch.float32) + dynamic_per_token_scaled_fp8_quant(ops_out, x, ops_scales, scale_ub) + + torch.testing.assert_close(ref_scales, ops_scales) + # allow 1 ULP difference + assert ( + ref_out.view(torch.uint8).to(torch.int16) + - ops_out.view(torch.uint8).to(torch.int16) + ).abs().max() <= 1 + + +class TestDynamicPerTokenScaledFp8QuantIntegration: + def test_kernel_registration_integration(self): + from vllm.kernels.helion.register import get_registered_kernels + + registered_kernels = get_registered_kernels() + assert "dynamic_per_token_scaled_fp8_quant" in registered_kernels + + kernel_wrapper = registered_kernels["dynamic_per_token_scaled_fp8_quant"] + assert kernel_wrapper.op_name == "dynamic_per_token_scaled_fp8_quant" + assert kernel_wrapper._config_picker is not None + assert kernel_wrapper._mutates_args == ["result", "scale"] + + def test_fake_impl_functionality(self): + skip_if_platform_unsupported("dynamic_per_token_scaled_fp8_quant") + from vllm.kernels.helion.register import get_registered_kernels + + registered_kernels = get_registered_kernels() + kernel_wrapper = registered_kernels["dynamic_per_token_scaled_fp8_quant"] + fake_impl = kernel_wrapper._fake_impl + + args = _generate_fake_input(16, 4096) + assert fake_impl(*args) is None diff --git a/tests/kernels/helion/test_rms_norm_dynamic_per_token_quant.py b/tests/kernels/helion/test_rms_norm_dynamic_per_token_quant.py new file mode 100644 index 000000000000..3842419562c4 --- /dev/null +++ b/tests/kernels/helion/test_rms_norm_dynamic_per_token_quant.py @@ -0,0 +1,207 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Tests for the rms_norm_dynamic_per_token_quant helion kernel + +Run `pytest tests/kernels/helion/test_rms_norm_dynamic_per_token_quant.py`. +""" + +from typing import Any + +import pytest +import torch +from torch._subclasses.fake_tensor import FakeTensorMode + +from tests.kernels.helion.utils import skip_if_platform_unsupported +from vllm.kernels.helion.case_key import CaseKey +from vllm.kernels.helion.config_manager import ConfigManager +from vllm.kernels.helion.ops.rms_norm_dynamic_per_token_quant import ( + _pick_cache, + baseline, + pick_config, + rms_norm_dynamic_per_token_quant, +) +from vllm.platforms import current_platform +from vllm.utils.import_utils import has_helion +from vllm.utils.torch_utils import set_random_seed + +if not has_helion(): + pytest.skip( + "Helion is not installed. Install with: pip install vllm[helion]", + allow_module_level=True, + ) + + +def _generate_fake_input(num_tokens: int, hidden_size: int) -> tuple[Any, ...]: + with FakeTensorMode(): + input = torch.randn( + num_tokens, hidden_size, device="cuda", dtype=torch.bfloat16 + ) + result = torch.empty( + input.shape, device=input.device, dtype=current_platform.fp8_dtype() + ) + scale = torch.empty((num_tokens, 1), device=input.device, dtype=torch.float32) + scale_ub = torch.mean(input).to(torch.float32) + residual = torch.randn_like(input) + weight = torch.normal( + mean=1.0, + std=1.0, + size=(hidden_size,), + dtype=input.dtype, + device=input.device, + ) + epsilon = 1e-6 + args = (result, input, weight, scale, epsilon, scale_ub, residual) + return args + + +@pytest.fixture(autouse=True) +def reset_config_manager_singleton(): + ConfigManager.reset_instance() + ConfigManager() + yield + ConfigManager.reset_instance() + + +class TestRmsNormDynamicPerTokenQuantConfigPicker: + def setup_method(self): + _pick_cache.clear() + + def test_config_picker_exact_match(self): + config_keys = [ + CaseKey({"hidden_size": 2048, "num_tokens": 16}), + CaseKey({"hidden_size": 4096, "num_tokens": 16}), + ] + + args = _generate_fake_input(16, 4096) + selected_key = pick_config(args, config_keys) + assert selected_key == CaseKey({"hidden_size": 4096, "num_tokens": 16}) + + def test_config_picker_closest_match(self): + config_keys = [ + CaseKey({"hidden_size": 2048, "num_tokens": 16}), + CaseKey({"hidden_size": 2048, "num_tokens": 32}), + CaseKey({"hidden_size": 4096, "num_tokens": 16}), + CaseKey({"hidden_size": 4096, "num_tokens": 32}), + ] + + args = _generate_fake_input(20, 3000) + selected_key = pick_config(args, config_keys) + assert selected_key == CaseKey({"hidden_size": 2048, "num_tokens": 32}) + + def test_config_picker_no_configs(self): + config_keys: list[dict] = [] + + args = _generate_fake_input(16, 4096) + selected_key = pick_config(args, config_keys) + assert selected_key is None + + def test_config_picker_fallback_to_largest(self): + config_keys = [ + CaseKey({"hidden_size": 2048, "num_tokens": 16}), + CaseKey({"hidden_size": 4096, "num_tokens": 16}), + ] + + args = _generate_fake_input(32, 8192) + selected_key = pick_config(args, config_keys) + assert selected_key == CaseKey({"hidden_size": 4096, "num_tokens": 16}) + + +DTYPES = [torch.bfloat16, torch.float] +QUANT_DTYPES = [torch.int8, current_platform.fp8_dtype()] +VEC_HIDDEN_SIZES = [1024, 1025, 1027, 1029] +# Avoid combinatorial explosion with full Cartesian product +NUM_TOKENS_HIDDEN_SIZES = [ + *[(1, i) for i in [1, 64, *VEC_HIDDEN_SIZES, 5120, 5137]], + *[(2048, i) for i in [1, 64, *VEC_HIDDEN_SIZES, 5137]], + *[(4096, i) for i in [1, 64, 5137]], +] + +ADD_RESIDUAL = [False, True] +SCALE_UBS = [True, False] +SEEDS = [0] + +EPS = 1e-6 + + +class TestRmsNormDynamicPerTokenQuantCorrectness: + @pytest.mark.parametrize("num_tokens, hidden_size", NUM_TOKENS_HIDDEN_SIZES) + @pytest.mark.parametrize("add_residual", ADD_RESIDUAL) + @pytest.mark.parametrize("has_scale_ub", SCALE_UBS) + @pytest.mark.parametrize("dtype", DTYPES) + @pytest.mark.parametrize("quant_dtype", QUANT_DTYPES) + @pytest.mark.parametrize("seed", SEEDS) + def test_rms_norm_dynamic_per_token_quant( + self, + num_tokens: int, + hidden_size: int, + add_residual: bool, + has_scale_ub: bool, + dtype: torch.dtype, + quant_dtype: torch.dtype, + seed: int, + ) -> None: + skip_if_platform_unsupported("rms_norm_dynamic_per_token_quant") + + set_random_seed(seed) + + if has_scale_ub and quant_dtype != current_platform.fp8_dtype(): + # skip + return + + scale = 1 / (hidden_size) + x = torch.randn(num_tokens, hidden_size, dtype=dtype, device="cuda") * scale + weight = torch.normal( + mean=1.0, std=1.0, size=(hidden_size,), dtype=dtype, device=x.device + ) + residual = torch.randn_like(x) * scale if add_residual else None + scale_ub = ( + torch.mean(x).to(dtype=torch.float32, device="cuda") + if has_scale_ub + else None + ) + + ref_out = torch.empty(x.shape, device=x.device, dtype=quant_dtype) + ref_scales = torch.empty((x.shape[0], 1), device=x.device, dtype=torch.float32) + ref_residual = residual.clone() if residual is not None else None + baseline(ref_out, x, weight, ref_scales, EPS, scale_ub, ref_residual) + + ops_out = torch.empty(x.shape, device=x.device, dtype=quant_dtype) + ops_scales = torch.empty((x.shape[0], 1), device=x.device, dtype=torch.float32) + ops_residual = residual.clone() if residual is not None else None + rms_norm_dynamic_per_token_quant( + ops_out, x, weight, ops_scales, EPS, scale_ub, ops_residual + ) + + torch.testing.assert_close(ref_scales, ops_scales) + # allow 1 ULP difference + assert ( + ref_out.view(torch.uint8).to(torch.int16) + - ops_out.view(torch.uint8).to(torch.int16) + ).abs().max() <= 1 + + if add_residual: + torch.testing.assert_close(ref_residual, ops_residual) + + +class TestRmsNormDynamicPerTokenQuantIntegration: + def test_kernel_registration_integration(self): + from vllm.kernels.helion.register import get_registered_kernels + + registered_kernels = get_registered_kernels() + assert "rms_norm_dynamic_per_token_quant" in registered_kernels + + kernel_wrapper = registered_kernels["rms_norm_dynamic_per_token_quant"] + assert kernel_wrapper.op_name == "rms_norm_dynamic_per_token_quant" + assert kernel_wrapper._config_picker is not None + assert kernel_wrapper._mutates_args == ["result", "scale", "residual"] + + def test_fake_impl_functionality(self): + skip_if_platform_unsupported("rms_norm_dynamic_per_token_quant") + from vllm.kernels.helion.register import get_registered_kernels + + registered_kernels = get_registered_kernels() + kernel_wrapper = registered_kernels["rms_norm_dynamic_per_token_quant"] + fake_impl = kernel_wrapper._fake_impl + + args = _generate_fake_input(16, 4096) + assert fake_impl(*args) is None diff --git a/tests/kernels/helion/test_rms_norm_per_block_quant.py b/tests/kernels/helion/test_rms_norm_per_block_quant.py new file mode 100644 index 000000000000..4cb18d775985 --- /dev/null +++ b/tests/kernels/helion/test_rms_norm_per_block_quant.py @@ -0,0 +1,298 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Tests for the rms_norm_per_block_quant helion kernel + +Run `pytest tests/kernels/helion/test_rms_norm_per_block_quant.py`. +""" + +import itertools +from typing import Any + +import pytest +import torch +from torch._subclasses.fake_tensor import FakeTensorMode + +from tests.kernels.helion.utils import skip_if_platform_unsupported +from tests.kernels.quant_utils import FP8_DTYPE +from vllm.kernels.helion.case_key import CaseKey +from vllm.kernels.helion.config_manager import ConfigManager +from vllm.kernels.helion.ops.rms_norm_per_block_quant import ( + _pick_cache, + baseline, + pick_config, + rms_norm_per_block_quant, +) +from vllm.utils.import_utils import has_helion +from vllm.utils.torch_utils import set_random_seed + +if not has_helion(): + pytest.skip( + "Helion is not installed. Install with: pip install vllm[helion]", + allow_module_level=True, + ) + + +def _generate_fake_input( + num_tokens: int, hidden_size: int, group_size: int +) -> tuple[Any, ...]: + with FakeTensorMode(): + input = torch.randn( + (num_tokens, hidden_size), device="cuda", dtype=torch.bfloat16 + ) + result = torch.empty(input.shape, device=input.device, dtype=FP8_DTYPE) + scale = torch.empty( + (num_tokens, hidden_size // group_size), + device=input.device, + dtype=torch.float32, + ) + scale_ub = torch.mean(input).to(scale.dtype) + residual = torch.randn_like(input) + weight = torch.normal( + mean=1.0, + std=1.0, + size=(hidden_size,), + dtype=input.dtype, + device=input.device, + ) + epsilon = 1e-6 + args = ( + result, + input, + weight, + scale, + epsilon, + scale_ub, + residual, + group_size, + False, + ) + return args + + +@pytest.fixture(autouse=True) +def reset_config_manager_singleton(): + ConfigManager.reset_instance() + ConfigManager() + yield + ConfigManager.reset_instance() + + +class TestRmsNormPerBlockQuantConfigPicker: + def setup_method(self): + _pick_cache.clear() + + def test_config_picker_exact_match(self): + config_keys = [ + CaseKey({"hidden_size": 2048, "group_size": 64, "num_tokens": 16}), + CaseKey({"hidden_size": 4096, "group_size": 128, "num_tokens": 16}), + ] + + args = _generate_fake_input(16, 4096, 128) + selected_key = pick_config(args, config_keys) + assert selected_key == CaseKey( + {"hidden_size": 4096, "group_size": 128, "num_tokens": 16} + ) + + def test_config_picker_closest_match(self): + config_keys = [ + CaseKey({"hidden_size": 2048, "group_size": 64, "num_tokens": 16}), + CaseKey({"hidden_size": 2048, "group_size": 64, "num_tokens": 32}), + CaseKey({"hidden_size": 2048, "group_size": 128, "num_tokens": 16}), + CaseKey({"hidden_size": 2048, "group_size": 128, "num_tokens": 32}), + CaseKey({"hidden_size": 4096, "group_size": 64, "num_tokens": 16}), + CaseKey({"hidden_size": 4096, "group_size": 64, "num_tokens": 32}), + CaseKey({"hidden_size": 4096, "group_size": 128, "num_tokens": 16}), + CaseKey({"hidden_size": 4096, "group_size": 128, "num_tokens": 32}), + ] + + args = _generate_fake_input(20, 3000, 70) + selected_key = pick_config(args, config_keys) + assert selected_key == CaseKey( + {"hidden_size": 2048, "group_size": 64, "num_tokens": 32} + ) + + def test_config_picker_no_configs(self): + config_keys: list[dict] = [] + + args = _generate_fake_input(16, 4096, 128) + selected_key = pick_config(args, config_keys) + assert selected_key is None + + def test_config_picker_fallback_to_largest(self): + config_keys = [ + CaseKey({"hidden_size": 2048, "group_size": 64, "num_tokens": 16}), + CaseKey({"hidden_size": 2048, "group_size": 64, "num_tokens": 32}), + CaseKey({"hidden_size": 2048, "group_size": 128, "num_tokens": 16}), + CaseKey({"hidden_size": 2048, "group_size": 128, "num_tokens": 32}), + CaseKey({"hidden_size": 4096, "group_size": 64, "num_tokens": 16}), + CaseKey({"hidden_size": 4096, "group_size": 64, "num_tokens": 32}), + CaseKey({"hidden_size": 4096, "group_size": 128, "num_tokens": 16}), + CaseKey({"hidden_size": 4096, "group_size": 128, "num_tokens": 32}), + ] + + args = _generate_fake_input(64, 8192, 256) + selected_key = pick_config(args, config_keys) + assert selected_key == CaseKey( + {"hidden_size": 4096, "group_size": 128, "num_tokens": 32} + ) + + +DTYPES = [torch.bfloat16, torch.float] +QUANT_DTYPES = [torch.int8, FP8_DTYPE] +VEC_HIDDEN_SIZES = [64, 1024] +# Avoid combinatorial explosion with full Cartesian product +NUM_TOKENS_HIDDEN_SIZES = [ + *[(1, i) for i in [64, 128, 1024, 5120]], + *[(2048, i) for i in [64, 1024]], + *[(4096, i) for i in [64]], +] + +ADD_RESIDUAL = [False, True] +SCALE_UBS = [True, False] +GROUP_SIZES = [64, 128] +TMA_ALIGNMENTS = [0, 4] +SEEDS = [0] +EPS = 1e-6 + + +class TestRmsNormPerBlockQuantCorrectness: + @pytest.mark.parametrize("num_tokens, hidden_size", NUM_TOKENS_HIDDEN_SIZES) + @pytest.mark.parametrize("add_residual", ADD_RESIDUAL) + @pytest.mark.parametrize("has_scale_ub", SCALE_UBS) + @pytest.mark.parametrize("dtype", DTYPES) + @pytest.mark.parametrize("quant_dtype", QUANT_DTYPES) + @pytest.mark.parametrize("is_scale_transposed", [False, True]) + @pytest.mark.parametrize( + "group_size, tma_alignment", + [*itertools.product(GROUP_SIZES, TMA_ALIGNMENTS)], + ) + @pytest.mark.parametrize("seed", SEEDS) + def test_rms_norm_per_block_quant( + self, + num_tokens: int, + hidden_size: int, + add_residual: bool, + has_scale_ub: bool, + dtype: torch.dtype, + quant_dtype: torch.dtype, + is_scale_transposed: bool, + group_size: int, + tma_alignment: int, + seed: int, + ) -> None: + skip_if_platform_unsupported("rms_norm_per_block_quant") + + set_random_seed(seed) + + if hidden_size % group_size != 0: + # skip + return + + if tma_alignment != 0 and hidden_size // group_size % tma_alignment == 0: + # Skip tests where TMA alignment doesn't create extra padding to save time + return + + if has_scale_ub and quant_dtype != FP8_DTYPE: + # skip + return + + scale = 1 / (hidden_size) + input = torch.randn(num_tokens, hidden_size, dtype=dtype, device="cuda") * scale + weight = torch.normal( + mean=1.0, std=1.0, size=(hidden_size,), dtype=dtype, device=input.device + ) + residual = torch.randn_like(input) * scale if add_residual else None + scale_ub = ( + torch.mean(input).to(dtype=torch.float32, device="cuda") + if has_scale_ub + else None + ) + groups_per_row = hidden_size // group_size + + ref_residual = residual.clone() if residual is not None else None + ops_residual = residual.clone() if residual is not None else None + ref_out = torch.empty(input.shape, device=input.device, dtype=quant_dtype) + ops_out = ref_out.clone() + + if is_scale_transposed: + if tma_alignment == 0: + ref_scales = torch.empty( + (groups_per_row, num_tokens), + device=input.device, + dtype=torch.float32, + ).transpose(0, 1) + else: + tma_aligned_m = ( + (num_tokens + tma_alignment - 1) // tma_alignment * tma_alignment + ) + shape = (num_tokens, groups_per_row) + stride = (1, tma_aligned_m) + ref_scales = torch.empty_strided( + shape, stride, device=input.device, dtype=torch.float32 + ) + else: + ref_scales = torch.empty( + (num_tokens, groups_per_row), device=input.device, dtype=torch.float32 + ) + + ops_scales = ref_scales.clone() + + baseline( + ref_out, + input, + weight, + ref_scales, + EPS, + scale_ub, + ref_residual, + group_size, + is_scale_transposed, + ) + ref_scales = ref_scales.contiguous() + + rms_norm_per_block_quant( + ops_out, + input, + weight, + ops_scales, + EPS, + scale_ub, + ops_residual, + group_size, + is_scale_transposed, + ) + ops_scales = ops_scales.contiguous() + + torch.testing.assert_close(ref_scales, ops_scales) + # allow 1 ULP difference + assert ( + ref_out.view(torch.uint8).to(torch.int16) + - ops_out.view(torch.uint8).to(torch.int16) + ).abs().max() <= 1 + + if add_residual: + torch.testing.assert_close(ref_residual, ops_residual) + + +class TestRmsNormPerBlockQuantIntegration: + def test_kernel_registration_integration(self): + from vllm.kernels.helion.register import get_registered_kernels + + registered_kernels = get_registered_kernels() + assert "rms_norm_per_block_quant" in registered_kernels + + kernel_wrapper = registered_kernels["rms_norm_per_block_quant"] + assert kernel_wrapper.op_name == "rms_norm_per_block_quant" + assert kernel_wrapper._config_picker is not None + assert kernel_wrapper._mutates_args == ["result", "scale", "residual"] + + def test_fake_impl_functionality(self): + skip_if_platform_unsupported("rms_norm_per_block_quant") + from vllm.kernels.helion.register import get_registered_kernels + + registered_kernels = get_registered_kernels() + kernel_wrapper = registered_kernels["rms_norm_per_block_quant"] + fake_impl = kernel_wrapper._fake_impl + + args = _generate_fake_input(16, 4096, 128) + assert fake_impl(*args) is None diff --git a/tests/kernels/moe/modular_kernel_tools/common.py b/tests/kernels/moe/modular_kernel_tools/common.py index 646cff4c2d22..8041db68d752 100644 --- a/tests/kernels/moe/modular_kernel_tools/common.py +++ b/tests/kernels/moe/modular_kernel_tools/common.py @@ -328,7 +328,10 @@ def is_valid(self) -> tuple[bool, str | None]: if self.needs_deep_ep_v2() and not has_deep_ep_v2(): return False, "Needs DeepEP v2, but DeepEP v2 not available." if self.needs_deep_gemm() and not has_deep_gemm(): - return False, "Needs DeepGEMM, but DeepGEMM not available." + return ( + False, + "Needs DeepGEMM, but the current vLLM environment does not provide it.", + ) if self.needs_aiter() and not has_aiter(): # noqa: SIM103 return False, "Needs Aiter, but Aiter not available." if self.needs_mori() and not has_mori(): # noqa: SIM103 diff --git a/tests/kernels/moe/test_flydsl_moe.py b/tests/kernels/moe/test_flydsl_moe.py new file mode 100644 index 000000000000..7c51c3691311 --- /dev/null +++ b/tests/kernels/moe/test_flydsl_moe.py @@ -0,0 +1,179 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +# Copyright (c) 2025 FlyDSL Project Contributors + + +import importlib.util + +import pytest +import torch + +from vllm.model_executor.layers.fused_moe import fused_experts +from vllm.model_executor.layers.fused_moe.activation import MoEActivation +from vllm.model_executor.layers.fused_moe.config import ( + int4_w4a16_moe_quant_config, +) +from vllm.platforms import current_platform +from vllm.platforms.rocm import on_gfx950 + +if not (current_platform.is_rocm() and on_gfx950()): + pytest.skip("This test can only run on ROCm and gfx950.", allow_module_level=True) + +aiter_available = importlib.util.find_spec("aiter") is not None + +if not aiter_available: + pytest.skip("These tests require AITER to run.", allow_module_level=True) + +from vllm.model_executor.layers.fused_moe.fused_flydsl_moe import ( # noqa: E402 + fused_flydsl_moe, +) +from vllm.model_executor.layers.quantization.compressed_tensors.compressed_tensors_moe import ( # noqa: E402, E501 + compressed_tensors_moe_w4a16_flydsl, +) + +RoutingBuffers = tuple[ + torch.Tensor, # sorted_token_ids + torch.Tensor, # sorted_weights + torch.Tensor, # sorted_expert_ids + torch.Tensor, # num_valid_ids (shape [1], i32) + int, # sorted_size + int, # blocks +] + + +@pytest.mark.parametrize( + "num_tokens", [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384] +) +@pytest.mark.parametrize("inter_dim", [256, 512]) +def test_flydsl_moe(num_tokens: int, inter_dim: int): + device = "cuda" + topk = 8 + num_experts = 384 + hidden_size = 7168 + packed_factor = 8 + w13_num_shards = 2 + params_dtype = torch.bfloat16 + group_size = 32 + w2_scales_size = inter_dim + scale_factor = 0.01 + + num_groups_w2 = w2_scales_size // group_size + num_groups_w13 = hidden_size // group_size + + w13_weight = torch.randint( + 0, + 255, + (num_experts, hidden_size // packed_factor, w13_num_shards * inter_dim), + dtype=torch.int32, + device=device, + ) + + w2_weight = torch.randint( + 0, + 255, + (num_experts, inter_dim // packed_factor, hidden_size), + dtype=torch.int32, + device=device, + ) + w13_scale = scale_factor * torch.randn( + num_experts, + num_groups_w13, + w13_num_shards * inter_dim, + dtype=params_dtype, + device=device, + ) + w2_scale = scale_factor * torch.randn( + num_experts, num_groups_w2, hidden_size, dtype=params_dtype, device=device + ) + + w13_weight_packed = w13_weight.transpose(1, 2).contiguous().view(torch.uint8) + w2_weight_packed = w2_weight.transpose(1, 2).contiguous().view(torch.uint8) + w13_weight_scale = w13_scale.transpose(1, 2).contiguous() + w2_weight_scale = w2_scale.transpose(1, 2).contiguous() + + moe_quant_config = int4_w4a16_moe_quant_config( + w1_scale=w13_weight_scale, + w2_scale=w2_weight_scale, + w1_zp=None, + w2_zp=None, + block_shape=[0, group_size], + ) + score = torch.rand((num_tokens, num_experts), device=device, dtype=torch.float32) + topk_vals, topk_ids = torch.topk(score, k=topk, dim=1) + topk_weights = torch.softmax(topk_vals, dim=1).to(torch.float32) + x = torch.randn((num_tokens, hidden_size), dtype=torch.bfloat16, device=device) + out_ref = fused_experts( + x, + w13_weight_packed, + w2_weight_packed, + topk_weights=topk_weights, + topk_ids=topk_ids, + activation=MoEActivation.SILU, + apply_router_weight_on_input=False, + global_num_experts=num_experts, + expert_map=None, + quant_config=moe_quant_config, + ) + + w13 = w13_weight + w13 = compressed_tensors_moe_w4a16_flydsl._gptq_int32_to_flydsl_packed(w13) + w13 = w13.view(-1).contiguous() + + w2 = w2_weight + w2 = compressed_tensors_moe_w4a16_flydsl._gptq_int32_to_flydsl_packed(w2) + w2 = w2.view(-1).contiguous() + + w13_scale_flydsl = w13_scale + w2_scale_flydsl = w2_scale + + if group_size > 0 and w13_scale.dim() == 3 and w13_scale.shape[1] > 1: + E, G, N = w13_scale.shape + w13_scale_flydsl = ( + w13_scale_flydsl.view(E, G // 2, 2, N) + .permute(0, 1, 3, 2) + .contiguous() + .view(-1) + .contiguous() + ) + elif w13_scale.dim() == 3 and w13_scale.shape[1] == 1: + w13_scale_flydsl = w13_scale_flydsl.squeeze(1) + + if group_size > 0 and w2_scale.dim() == 3 and w2_scale.shape[1] > 1: + E, G, N = w2_scale.shape + w2_scale_flydsl = ( + w2_scale_flydsl.view(E, G // 2, 2, N) + .permute(0, 1, 3, 2) + .contiguous() + .view(-1) + .contiguous() + ) + elif w2_scale.dim() == 3 and w2_scale.shape[1] == 1: + w2_scale_flydsl = w2_scale_flydsl.squeeze(1) + + w13_scale_flydsl = w13_scale_flydsl.contiguous() + w2_scale_flydsl = w2_scale_flydsl.contiguous() + + w13.is_shuffled = True + w2.is_shuffled = True + + out = fused_flydsl_moe( + x, + w13, + w2, + num_experts, + inter_dim, + topk_weights, + topk_ids, + w1_scale=w13_scale_flydsl, + w2_scale=w2_scale_flydsl, + topk=topk_weights.shape[-1], + group_size=group_size, + doweight_stage1=False, + scale_is_bf16=True, + ) + + assert torch.allclose(out, out_ref, atol=0.5, rtol=0.1) + + +if __name__ == "__main__": + test_flydsl_moe(512, 256) diff --git a/tests/kernels/moe/test_mxfp4_moe.py b/tests/kernels/moe/test_mxfp4_moe.py index 11fd853f54f3..16b233b935e0 100644 --- a/tests/kernels/moe/test_mxfp4_moe.py +++ b/tests/kernels/moe/test_mxfp4_moe.py @@ -244,5 +244,224 @@ def test_mxfp4_experts_quant_basic(): print("PASSED") +def untile_cutlass_scale(scale_raw: torch.Tensor, rows: int, K: int) -> torch.Tensor: + """Convert CUTLASS tiled scale back to flat [M, K//32] layout. + + CUTLASS tiled layout: [numMTiles, numKTiles, 32(outerM), 4(innerM), 4(innerK)] + Produced by: padded.reshape(numMTiles, 4, 32, numKTiles, 4).permute(0,3,2,1,4) + To undo: tiled.permute(0, 3, 2, 1, 4).reshape(padded_M, padded_sK) + """ + num_scale_cols = K // MXFP4_BLOCK_SIZE + num_m_tiles = (rows + 127) // 128 + num_k_tiles = (num_scale_cols + 3) // 4 + padded_M = num_m_tiles * 128 + padded_sK = num_k_tiles * 4 + + scale_bytes = scale_raw.view(torch.uint8).flatten() + total_bytes = padded_M * padded_sK + tiled = scale_bytes[:total_bytes].reshape(num_m_tiles, num_k_tiles, 32, 4, 4) + undone = tiled.permute(0, 3, 2, 1, 4).contiguous() + return undone.reshape(padded_M, padded_sK)[:rows, :num_scale_cols] + + +def compute_reference_e8m0_scale(block_max: float) -> int: + """Compute the expected OCP MX spec E8M0 scale for a given block max. + + The CUTLASS kernel uses round-to-nearest on the mantissa: + rounded_bits = (float_bits + (1 << 21)) & 0xFF800000 + biased_exp = (rounded_bits >> 23) & 0xFF + scale_exp = max(biased_exp - 2, 0) + + This ensures max_val / scale <= 6.0 for most inputs. + """ + import struct + + if block_max <= 0: + return 0 + # Replicate the kernel's rounding logic in Python + float_bytes = struct.pack("f", block_max) + max_bits = struct.unpack("I", float_bytes)[0] + rounded_bits = (max_bits + (1 << 21)) & 0xFF800000 + biased_exp = (rounded_bits >> 23) & 0xFF + scale_exp = max(int(biased_exp) - 2, 0) + scale_exp = min(scale_exp, 254) + return scale_exp + + +@pytest.mark.skipif( + not is_sm100_supported(), + reason="mxfp4_experts_quant requires CUDA SM100", +) +@pytest.mark.parametrize("k", [256, 7168]) +@pytest.mark.parametrize("m", [16, 64]) +def test_mxfp4_experts_quant_e8m0_scale_correctness(m, k): + """ + Test that mxfp4_experts_quant computes E8M0 block scales correctly + per OCP MX spec (not the NVFP4 formula). + + The old buggy kernel used: floor(log2(max/6)) + 127 + The fixed kernel uses: round_nearest_exp(max) - 2 + + This test verifies: + 1. Scales match the expected OCP MX formula for all blocks + 2. No block max exceeds the representable range (no unexpected saturation) + 3. Reconstruction error is within expected bounds for MXFP4 + """ + device = "cuda" + + # Generate input with controlled range + input_tensor = torch.randn(m, k, device=device, dtype=torch.bfloat16) * 0.5 + + # Quantize + num_experts = 1 + expert_offsets = torch.tensor([0, m], device=device, dtype=torch.int32) + num_k_tiles = (k // MXFP4_BLOCK_SIZE + 3) // 4 + blockscale_offsets = torch.tensor( + [0, align(m, 128) * num_k_tiles], device=device, dtype=torch.int32 + ) + + output_fp4, output_sf = ops.mxfp4_experts_quant( + input_tensor, expert_offsets, blockscale_offsets, num_experts, topk=1 + ) + + # Untile scale to flat layout for verification + scale_flat = untile_cutlass_scale(output_sf, m, k) + assert scale_flat.shape == (m, k // MXFP4_BLOCK_SIZE) + + # Verify each block's scale matches the OCP MX spec formula + num_blocks = k // MXFP4_BLOCK_SIZE + mismatches = 0 + buggy_pattern = 0 # count blocks where scale is 1-2 lower than expected + + for row in range(m): + for blk in range(num_blocks): + block_start = blk * MXFP4_BLOCK_SIZE + block_end = block_start + MXFP4_BLOCK_SIZE + block_max = ( + input_tensor[row, block_start:block_end].float().abs().max().item() + ) + + actual_scale = scale_flat[row, blk].item() + expected_scale = compute_reference_e8m0_scale(block_max) + + if actual_scale != expected_scale: + mismatches += 1 + if actual_scale < expected_scale: + buggy_pattern += 1 + + total_blocks = m * num_blocks + match_rate = (total_blocks - mismatches) / total_blocks + + print( + f" m={m}, k={k}: scale match rate = {match_rate * 100:.2f}% " + f"({mismatches}/{total_blocks} mismatches)" + ) + + # The fixed kernel should match the reference formula exactly + assert match_rate > 0.99, ( + f"E8M0 scale match rate too low: {match_rate * 100:.2f}%. " + f"Buggy pattern (scale too low): {buggy_pattern}/{mismatches}. " + f"This suggests the NVFP4 formula bug is present." + ) + + # Extra check: if most mismatches show scale < expected, it's the old bug + if mismatches > 0: + assert buggy_pattern / mismatches < 0.5, ( + f"Most scale mismatches show scale too LOW ({buggy_pattern}/{mismatches}). " + "This is the signature of the NVFP4 formula bug in nvfp4_utils.cuh." + ) + + # Verify reconstruction error is within MXFP4 expected bounds + # Dequantize and check cosine similarity + fp4_lut = torch.tensor( + [0, 0.5, 1, 1.5, 2, 3, 4, 6, 0, -0.5, -1, -1.5, -2, -3, -4, -6], + device=device, + dtype=torch.float32, + ) + lo = (output_fp4 & 0x0F).long() + hi = ((output_fp4 >> 4) & 0x0F).long() + unpacked = torch.stack([lo, hi], dim=-1).reshape(m, k) + fp4_vals = fp4_lut[unpacked] + + scales_expanded = 2.0 ** (scale_flat.float() - 127.0) + scales_expanded = scales_expanded.unsqueeze(-1).expand(-1, -1, MXFP4_BLOCK_SIZE) + scales_expanded = scales_expanded.reshape(m, k) + recon = (fp4_vals * scales_expanded).bfloat16() + + # Cosine similarity should be > 0.99 for well-behaved MXFP4 quantization + cos_sim = torch.nn.functional.cosine_similarity( + recon.float().flatten().unsqueeze(0), + input_tensor.float().flatten().unsqueeze(0), + ).item() + max_abs_diff = (recon.float() - input_tensor.float()).abs().max().item() + + print( + f" Reconstruction: cosine_sim={cos_sim:.6f}, max_abs_diff={max_abs_diff:.4f}" + ) + + assert cos_sim > 0.99, ( + f"Reconstruction cosine similarity too low: {cos_sim:.6f}. " + f"Expected > 0.99 for correct MXFP4 quantization." + ) + # With correct E8M0, max abs diff should be bounded by scale * 6 + # (worst case: value just below threshold rounds to wrong FP4 code) + assert max_abs_diff < 1.0, ( + f"Max reconstruction error too large: {max_abs_diff:.4f}. " + "Likely caused by incorrect E8M0 scale (values saturating to ±6)." + ) + + +@pytest.mark.skipif( + not is_sm100_supported(), + reason="mxfp4_experts_quant requires CUDA SM100", +) +def test_mxfp4_experts_quant_no_saturation(): + """ + Test that the E8M0 scale is large enough to avoid unexpected saturation. + + With the buggy NVFP4 formula, the scale was too small causing most values + to saturate to ±6 in FP4. The fixed OCP MX formula should ensure that + block_max / scale <= 6.0 (the max E2M1 value) in almost all cases. + """ + device = "cuda" + + m, k = 128, 1024 + # Use inputs with known range to make saturation detectable + input_tensor = torch.randn(m, k, device=device, dtype=torch.bfloat16) * 0.5 + + num_experts = 1 + expert_offsets = torch.tensor([0, m], device=device, dtype=torch.int32) + num_k_tiles = (k // MXFP4_BLOCK_SIZE + 3) // 4 + blockscale_offsets = torch.tensor( + [0, align(m, 128) * num_k_tiles], device=device, dtype=torch.int32 + ) + + output_fp4, output_sf = ops.mxfp4_experts_quant( + input_tensor, expert_offsets, blockscale_offsets, num_experts, topk=1 + ) + + # Check saturation rate: count FP4 values that are ±6 (codes 7 and 15) + lo = output_fp4 & 0x0F + hi = (output_fp4 >> 4) & 0x0F + # Code 7 = +6.0, code 15 = -6.0 + saturated = ((lo == 7) | (lo == 15) | (hi == 7) | (hi == 15)).sum().item() + total_values = m * k + saturation_rate = saturated / total_values + + print( + f" Saturation rate: {saturation_rate * 100:.2f}% " + f"({saturated}/{total_values} values at ±6)" + ) + + # For Gaussian input with std=0.5, saturation should be very rare + # (±6 * scale is far from the typical range). + # The buggy kernel had ~30-50% saturation; fixed should be < 5%. + assert saturation_rate < 0.05, ( + f"FP4 saturation rate too high: {saturation_rate * 100:.2f}%. " + "This suggests the E8M0 scale is too small (NVFP4 formula bug). " + "Expected < 5% for Gaussian(0, 0.5) input with correct OCP MX scale." + ) + + if __name__ == "__main__": pytest.main([__file__, "-v", "-s"]) diff --git a/tests/kernels/quantization/test_awq.py b/tests/kernels/quantization/test_awq.py index 3bf59dea3097..a8977958023a 100644 --- a/tests/kernels/quantization/test_awq.py +++ b/tests/kernels/quantization/test_awq.py @@ -27,23 +27,3 @@ def test_awq_dequantize_opcheck(monkeypatch: pytest.MonkeyPatch): torch.ops._C.awq_dequantize, (qweight, scales, zeros, split_k_iters, thx, thy), ) - - -@pytest.mark.skip(reason="Not working; needs investigation.") -@pytest.mark.skipif( - not hasattr(torch.ops._C, "awq_gemm"), - reason="AWQ is not supported on this GPU type.", -) -def test_awq_gemm_opcheck(monkeypatch: pytest.MonkeyPatch): - with monkeypatch.context() as m: - m.setenv("VLLM_USE_TRITON_AWQ", "0") - input = torch.rand((2, 8192), device="cuda", dtype=torch.float16) - qweight = torch.randint( - -2000000000, 2000000000, (8192, 256), device="cuda", dtype=torch.int32 - ) - scales = torch.empty((64, 2048), device="cuda", dtype=torch.float16) - qzeros = torch.randint( - -2000000000, 2000000000, (64, 256), device="cuda", dtype=torch.int32 - ) - split_k_iters = 8 - opcheck(torch.ops._C.awq_gemm, (input, qweight, scales, qzeros, split_k_iters)) diff --git a/tests/kernels/quantization/test_cutlass_scaled_mm.py b/tests/kernels/quantization/test_cutlass_scaled_mm.py index a937c30fed74..25893311afca 100644 --- a/tests/kernels/quantization/test_cutlass_scaled_mm.py +++ b/tests/kernels/quantization/test_cutlass_scaled_mm.py @@ -245,8 +245,6 @@ def test_cutlass_fp8_blockwise_scale_gemm( return if m % a_scale_group_shape[0] != 0 or k % a_scale_group_shape[1] != 0: return - if m % 4 != 0 and current_platform.has_device_capability(100): - return cutlass_fp8_gemm_helper(m, n, k, a_scale_group_shape, b_scale_group_shape, use_bias) diff --git a/tests/kernels/quantization/test_ggml.py b/tests/kernels/quantization/test_ggml.py deleted file mode 100644 index 0dc24187f2b3..000000000000 --- a/tests/kernels/quantization/test_ggml.py +++ /dev/null @@ -1,54 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -import gguf -import pytest -import torch - -from tests.kernels.utils import opcheck -from vllm import _custom_ops as ops # noqa: F401 - - -@pytest.mark.parametrize("quant_type", [12]) -def test_ggml_opcheck(quant_type): - block_size, type_size = gguf.GGML_QUANT_SIZES[quant_type] - shape = [256, 1152] - qweight = torch.randint(0, 100, shape, device="cuda", dtype=torch.uint8) - m = qweight.shape[0] - n = qweight.shape[1] // type_size * block_size - opcheck(torch.ops._C.ggml_dequantize, (qweight, quant_type, m, n, torch.float16)) - - x = torch.rand((m, 512), device="cuda", dtype=torch.float16) - opcheck(torch.ops._C.ggml_mul_mat_a8, (qweight, x, quant_type, qweight.shape[0])) - opcheck( - torch.ops._C.ggml_mul_mat_vec_a8, (qweight, x, quant_type, qweight.shape[0]) - ) - - shape = [256, 1024, 336] - qweight = torch.randint(0, 100, shape, device="cuda", dtype=torch.uint8) - x = torch.rand((1, 1024), device="cuda", dtype=torch.float16) - sorted_token_ids = torch.arange(776, device="cuda") - expert_ids = torch.randint(0, 256, (194,), device="cuda") - num_tokens_post_padded = torch.tensor([1], dtype=torch.int64, device="cuda") - - opcheck( - torch.ops._C.ggml_moe_a8, - ( - x, - qweight, - sorted_token_ids, - expert_ids, - num_tokens_post_padded, - quant_type, - qweight.shape[0], - 1, - x.shape[0], - ), - ) - - topk_ids = torch.zeros((1, 1), device="cuda", dtype=torch.int32) - - opcheck( - torch.ops._C.ggml_moe_a8_vec, - (x, qweight, topk_ids, 1, quant_type, qweight.shape[0], x.shape[0]), - ) diff --git a/tests/kernels/quantization/test_gguf.py b/tests/kernels/quantization/test_gguf.py deleted file mode 100644 index 912d5fee4e59..000000000000 --- a/tests/kernels/quantization/test_gguf.py +++ /dev/null @@ -1,207 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project - -from pathlib import Path - -import pytest -import torch -from gguf import GGMLQuantizationType, GGUFReader, ReaderTensor, dequantize -from huggingface_hub import snapshot_download - -import vllm._custom_ops as ops -from vllm.model_executor.layers.fused_moe import fused_experts -from vllm.model_executor.layers.quantization.gguf import _fused_moe_gguf -from vllm.utils.torch_utils import set_random_seed - -GGUF_SAMPLE = snapshot_download("Isotr0py/test-gguf-sample") -GGUF_SAMPLE_MOE = snapshot_download("SzymonOzog/test-gguf-moe-sample") - - -def get_gguf_sample_tensors( - hidden_size: int, quant_type: GGMLQuantizationType -) -> list[ReaderTensor]: - sample_dir = GGUF_SAMPLE - filename = f"Quant_{quant_type.name}_{hidden_size}.gguf" - sample_file = Path(sample_dir) / filename - return GGUFReader(sample_file).tensors - - -def get_gguf_MoE_tensors( - hidden_size: int, quant_type: GGMLQuantizationType -) -> list[ReaderTensor]: - sample_dir = GGUF_SAMPLE_MOE - filename = f"Quant_{quant_type.name}_{hidden_size}.gguf" - sample_file = Path(sample_dir) / filename - return GGUFReader(sample_file).tensors - - -DTYPES = [torch.bfloat16] # [torch.half, torch.bfloat16, torch.float32] -# Hidden_size for testing, must match the sample file in HF repo, -# we have `hidden_size = 256, 1024` for test in HF repo currently. -HIDDEN_SIZES = [256, 1024] -NUM_TOKENS = [7, 2050] # Arbitrary values for testing -SEEDS = [0] -QUANT_TYPES = [ - # i-matrix - GGMLQuantizationType.IQ1_M, - GGMLQuantizationType.IQ1_S, - GGMLQuantizationType.IQ2_S, - GGMLQuantizationType.IQ2_XS, - GGMLQuantizationType.IQ3_S, - GGMLQuantizationType.IQ3_XXS, - GGMLQuantizationType.IQ4_NL, - GGMLQuantizationType.IQ4_XS, - # k-quants - GGMLQuantizationType.Q2_K, - GGMLQuantizationType.Q3_K, - GGMLQuantizationType.Q4_K, - GGMLQuantizationType.Q5_K, - GGMLQuantizationType.Q6_K, - # standard quantization - GGMLQuantizationType.Q4_0, - GGMLQuantizationType.Q5_0, - GGMLQuantizationType.Q8_0, -] - - -@pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) -@pytest.mark.parametrize("dtype", DTYPES) -@pytest.mark.parametrize("quant_type", QUANT_TYPES) -@torch.inference_mode() -def test_dequantize( - hidden_size: int, dtype: torch.dtype, quant_type: GGMLQuantizationType -): - tensors = get_gguf_sample_tensors(hidden_size, quant_type) - for tensor in tensors: - shape_str = tensor.name.split("_")[-1] - shape = map(int, shape_str.split("x")) - - ref_output = torch.tensor( - dequantize(tensor.data, quant_type), device="cuda" - ).to(dtype) - output = ops.ggml_dequantize( - torch.tensor(tensor.data, device="cuda"), quant_type, *list(shape), dtype - ) - - torch.testing.assert_close(output, ref_output, atol=1e-2, rtol=4e-2) - - -@pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) -@pytest.mark.parametrize("dtype", DTYPES) -@pytest.mark.parametrize("quant_type", QUANT_TYPES) -@torch.inference_mode() -def test_mmvq(hidden_size: int, dtype: torch.dtype, quant_type: GGMLQuantizationType): - set_random_seed(0) - - tensors = get_gguf_sample_tensors(hidden_size, quant_type) - x = torch.rand((1, hidden_size), dtype=dtype, device="cuda") - for tensor in tensors: - weight = torch.tensor(dequantize(tensor.data, quant_type), device="cuda").to( - dtype - ) - ref_output = x @ weight.T - - qweight = torch.tensor(tensor.data, device="cuda") - output = ops.ggml_mul_mat_vec_a8(qweight, x, quant_type, qweight.shape[0]).to( - dtype - ) - - torch.testing.assert_close(output, ref_output, atol=1, rtol=1e-1) - - -@pytest.mark.parametrize("num_tokens", NUM_TOKENS) -@pytest.mark.parametrize("hidden_size", HIDDEN_SIZES) -@pytest.mark.parametrize("dtype", DTYPES) -@pytest.mark.parametrize( - "quant_type", - [ - # k-quants - GGMLQuantizationType.Q2_K, - GGMLQuantizationType.Q3_K, - GGMLQuantizationType.Q4_K, - GGMLQuantizationType.Q5_K, - GGMLQuantizationType.Q6_K, - # standard quants - GGMLQuantizationType.Q4_0, - GGMLQuantizationType.Q5_0, - GGMLQuantizationType.Q8_0, - ], -) -@torch.inference_mode() -def test_mmq( - num_tokens: int, - hidden_size: int, - dtype: torch.dtype, - quant_type: GGMLQuantizationType, -): - set_random_seed(0) - - tensors = get_gguf_sample_tensors(hidden_size, quant_type) - x = torch.rand((num_tokens, hidden_size), dtype=dtype, device="cuda") - for tensor in tensors: - weight = torch.tensor(dequantize(tensor.data, quant_type), device="cuda").to( - dtype - ) - ref_output = x @ weight.T - - qweight = torch.tensor(tensor.data, device="cuda") - output = ops.ggml_mul_mat_a8(qweight, x, quant_type, qweight.shape[0]) - atols = {torch.half: 1, torch.bfloat16: 1.5, torch.float: 1.2} - # test matrix has inputs centered around 0 and lower precision from - # bfloat16 tends to accumulate and can greatly inflate rtol - # since outputs are also very close to 0 - rtols = {torch.half: 1e-1, torch.bfloat16: 1e4, torch.float: 2e1} - torch.testing.assert_close( - output, ref_output, atol=atols[dtype], rtol=rtols[dtype] - ) - - -@pytest.mark.parametrize("num_tokens", NUM_TOKENS) -@pytest.mark.parametrize("hidden_size", [512]) -@pytest.mark.parametrize("top_k", [4, 8]) -@pytest.mark.parametrize("dtype", DTYPES) -@pytest.mark.parametrize("quant_type", QUANT_TYPES) -@torch.inference_mode() -def test_moe( - num_tokens: int, - hidden_size: int, - dtype: torch.dtype, - quant_type: GGMLQuantizationType, - top_k: int, -): - set_random_seed(0) - H, E = 1024, 256 - - x = torch.rand((num_tokens, H), dtype=dtype, device="cuda") - - topk_weights = torch.rand(num_tokens, top_k, device="cuda", dtype=dtype) - topk_ids = torch.randint( - 0, E, (num_tokens, top_k), device="cuda", dtype=torch.int32 - ) - - tensors = get_gguf_MoE_tensors(hidden_size, quant_type) - - w13 = tensors[0] - w2 = tensors[1] - - w13_dequant = torch.tensor(dequantize(w13.data, quant_type), device="cuda").to( - dtype - ) - - w2_dequant = torch.tensor(dequantize(w2.data, quant_type), device="cuda").to(dtype) - - output = _fused_moe_gguf( - x, - torch.tensor(w13.data, device="cuda"), - torch.tensor(w2.data, device="cuda"), - topk_weights, - topk_ids, - quant_type, - quant_type, - "silu", - ) - - ref_output = fused_experts( - x, w13_dequant, w2_dequant, topk_weights, topk_ids - ).reshape(output.shape) - torch.testing.assert_close(output, ref_output, atol=1, rtol=1e-1) diff --git a/tests/kernels/quantization/test_marlin_tile_padding.py b/tests/kernels/quantization/test_marlin_tile_padding.py new file mode 100644 index 000000000000..62b18d88ac53 --- /dev/null +++ b/tests/kernels/quantization/test_marlin_tile_padding.py @@ -0,0 +1,470 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Tests for Marlin thread-tile padding of TP-sharded weight shapes. + +Run `pytest tests/kernels/quantization/test_marlin_tile_padding.py`. +""" + +import pytest +import torch + +from vllm import _custom_ops as ops +from vllm.model_executor.layers.quantization.utils.marlin_utils import ( + GPTQ_MARLIN_TILE, + apply_gptq_marlin_linear, + marlin_make_empty_g_idx, + marlin_make_workspace_new, + marlin_pad_qweight, + marlin_pad_scales, + marlin_padded_nk, + marlin_permute_scales, + marlin_repacked_nk, + marlin_zero_points, +) +from vllm.model_executor.layers.quantization.utils.marlin_utils_fp4 import ( + apply_fp4_marlin_linear, + is_fp4_marlin_supported, + prepare_fp4_layer_for_marlin, +) +from vllm.model_executor.layers.quantization.utils.marlin_utils_fp8 import ( + apply_fp8_marlin_linear, + apply_mxfp8_marlin_linear, + is_fp8_marlin_supported, + prepare_fp8_layer_for_marlin, + prepare_mxfp8_layer_for_marlin, +) +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + gptq_pack, + gptq_quantize_weights, + quantize_weights, +) +from vllm.platforms import current_platform +from vllm.scalar_type import scalar_types + +# (size_n, size_k) rank-local shapes that violate Marlin tile alignment, +# e.g. produced by TP-sharding dims that are valid at TP=1. +ODD_SHAPES = [ + (200, 288), # N padded + (256, 208), # K padded + (200, 208), # both padded + (4640, 512), # Nemotron-Super-120B q_proj shard at TP=4 +] +ALIGNED_SHAPES = [(64, 128), (128, 64), (256, 256), (4608, 4096)] + + +def _is_tile_aligned(size_n: int, size_k: int) -> bool: + return (size_n % 64 == 0 and size_k % 128 == 0) or ( + size_n % 128 == 0 and size_k % 64 == 0 + ) + + +@pytest.mark.parametrize("shape", ODD_SHAPES + ALIGNED_SHAPES) +@pytest.mark.parametrize("group_size", [-1, 16, 32, 64, 128]) +def test_marlin_padded_nk(shape, group_size): + size_n, size_k = shape + padded_n, padded_k = marlin_padded_nk(size_n, size_k, group_size) + + assert padded_n >= size_n and padded_k >= size_k + assert _is_tile_aligned(padded_n, padded_k) + if group_size > 0: + assert padded_k % group_size == 0 + + # Aligned shapes must pass through unchanged (zero hot-path cost). + if _is_tile_aligned(size_n, size_k) and ( + group_size <= 0 or size_k % group_size == 0 + ): + assert (padded_n, padded_k) == (size_n, size_k) + + # Minimal: no valid shape with a smaller padded area exists. + area = padded_n * padded_k + for cand_n in range(size_n, padded_n + 1): + for cand_k in range(size_k, padded_k + 1): + if ( + _is_tile_aligned(cand_n, cand_k) + and (group_size <= 0 or cand_k % group_size == 0) + and cand_n * cand_k < area + ): + pytest.fail(f"({cand_n}, {cand_k}) beats ({padded_n}, {padded_k})") + + # Apply-time derivation from the repacked-tensor shape must round-trip. + for num_bits in (4, 8): + pack_factor = 32 // num_bits + repacked_shape = ( + padded_k // GPTQ_MARLIN_TILE, + padded_n * GPTQ_MARLIN_TILE // pack_factor, + ) + repacked = torch.empty(repacked_shape, device="meta") + assert marlin_repacked_nk(repacked, num_bits) == (padded_n, padded_k) + + +def test_marlin_pad_helpers_shapes(): + size_n, size_k, group_size = 200, 208, 16 + padded_n, padded_k = marlin_padded_nk(size_n, size_k, group_size) + + qweight = torch.zeros(size_k // 8, size_n, dtype=torch.int32) + padded = marlin_pad_qweight(qweight, size_n, size_k, padded_n, padded_k) + assert padded.shape == (padded_k // 8, padded_n) + + scales = torch.ones(size_k // group_size, size_n) + padded = marlin_pad_scales(scales, size_n, size_k, padded_n, padded_k, group_size) + assert padded.shape == (padded_k // group_size, padded_n) + assert padded[:, size_n:].abs().sum() == 0 + + channelwise = torch.ones(1, size_n) + padded = marlin_pad_scales(channelwise, size_n, size_k, padded_n, padded_k, -1) + assert padded.shape == (1, padded_n) + + +def _gpu_marlin_unsupported() -> bool: + return not ( + current_platform.is_cuda() and current_platform.has_device_capability(80) + ) + + +@pytest.mark.skipif( + _gpu_marlin_unsupported() or not is_fp8_marlin_supported(), + reason="FP8 Marlin is not supported on this GPU type.", +) +@pytest.mark.parametrize("shape", ODD_SHAPES) +@pytest.mark.parametrize("use_bias", [False, True]) +def test_fp8_marlin_padded_round_trip(shape, use_bias): + size_n, size_k = shape + dtype = torch.float16 + layer = torch.nn.Module() + layer.output_size_per_partition = size_n + layer.input_size_per_partition = size_k + layer.orig_dtype = dtype + + weight = torch.randn(size_k, size_n, dtype=dtype, device="cuda") / size_k**0.5 + scale = weight.abs().max() / 448 + weight_fp8 = (weight / scale).to(torch.float8_e4m3fn) + layer.weight = torch.nn.Parameter(weight_fp8, requires_grad=False) + layer.weight_scale = torch.nn.Parameter( + scale.to(torch.float32), requires_grad=False + ) + bias = None + if use_bias: + bias = torch.randn(size_n, dtype=dtype, device="cuda") + layer.bias = torch.nn.Parameter(bias.clone(), requires_grad=False) + + prepare_fp8_layer_for_marlin(layer, size_k_first=True) + + x = torch.randn(8, size_k, dtype=dtype, device="cuda") + output = apply_fp8_marlin_linear( + input=x, + weight=layer.weight, + weight_scale=layer.weight_scale, + workspace=layer.workspace, + size_n=size_n, + size_k=size_k, + bias=layer.bias if use_bias else None, + ) + ref = x @ (weight_fp8.to(dtype) * scale.to(dtype)) + if use_bias: + ref = ref + bias + + assert output.shape == (8, size_n) + torch.testing.assert_close(output, ref, rtol=2e-2, atol=2e-2) + + +def _dequant_fp4(packed: torch.Tensor, dtype: torch.dtype) -> torch.Tensor: + """Dequantize packed e2m1 nibbles (N, K // 2) -> (N, K) in dtype.""" + lo = (packed & 0b10000000) | ((packed & 0b01110000) >> 2) + lo = lo.view(torch.float8_e4m3fn).to(dtype) * (2**6) + hi_bits = packed << 4 + hi = (hi_bits & 0b10000000) | ((hi_bits & 0b01110000) >> 2) + hi = hi.view(torch.float8_e4m3fn).to(dtype) * (2**6) + return torch.cat([hi.unsqueeze(2), lo.unsqueeze(2)], 2).view(packed.size(0), -1) + + +@pytest.mark.skipif( + _gpu_marlin_unsupported() or not is_fp4_marlin_supported(), + reason="FP4 Marlin is not supported on this GPU type.", +) +@pytest.mark.parametrize("shape", ODD_SHAPES) +def test_nvfp4_marlin_padded_round_trip(shape): + size_n, size_k = shape + group_size = 16 + dtype = torch.float16 + layer = torch.nn.Module() + layer.output_size_per_partition = size_n + layer.input_size_per_partition = size_k + layer.params_dtype = dtype + + packed = torch.randint( + 0, 256, (size_n, size_k // 2), dtype=torch.uint8, device="cuda" + ) + scales = (torch.rand(size_n, size_k // group_size, device="cuda") + 0.25).to( + torch.float8_e4m3fn + ) + global_scale = torch.tensor([0.002], dtype=torch.float32, device="cuda") + + ref_weight = ( + _dequant_fp4(packed, dtype) + * scales.to(dtype).repeat_interleave(group_size, 1) + * global_scale.to(dtype) + ) + + layer.weight = torch.nn.Parameter(packed, requires_grad=False) + layer.weight_scale = torch.nn.Parameter(scales, requires_grad=False) + layer.weight_global_scale = torch.nn.Parameter(global_scale, requires_grad=False) + + prepare_fp4_layer_for_marlin(layer) + + x = torch.randn(8, size_k, dtype=dtype, device="cuda") / size_k**0.5 + output = apply_fp4_marlin_linear( + input=x, + weight=layer.weight, + weight_scale=layer.weight_scale, + weight_global_scale=layer.weight_global_scale, + workspace=layer.workspace, + size_n=size_n, + size_k=size_k, + ) + ref = x @ ref_weight.T + + assert output.shape == (8, size_n) + torch.testing.assert_close(output, ref, rtol=2e-2, atol=2e-2) + + +@pytest.mark.skipif( + _gpu_marlin_unsupported(), + reason="Marlin is not supported on this GPU type.", +) +@pytest.mark.parametrize("shape", ODD_SHAPES) +@pytest.mark.parametrize("group_size", [-1, 128]) +def test_gptq_marlin_padded_round_trip(shape, group_size): + """Pad-then-repack a GPTQ int4 weight the way MarlinLinearKernel does and + check the GEMM against the dequantized reference. + + Symmetric int4's quantized zero decodes to -8, so this exercises the + zero-padded-scales cancellation, not just zero weights. + """ + size_n, size_k = shape + if group_size > 0 and size_k % group_size != 0: + pytest.skip("group must divide the rank-local K (not fixable by padding)") + dtype = torch.float16 + quant_type = scalar_types.uint4b8 + device = torch.device("cuda") + + weight = torch.randn(size_k, size_n, dtype=dtype, device=device) / size_k**0.5 + w_ref, q_w, s, _, _ = gptq_quantize_weights( + weight, quant_type, group_size, act_order=False + ) + qweight = gptq_pack(q_w, quant_type.size_bits, size_k, size_n) + + padded_n, padded_k = marlin_padded_nk(size_n, size_k, group_size) + qweight = marlin_pad_qweight(qweight, size_n, size_k, padded_n, padded_k) + marlin_qweight = ops.gptq_marlin_repack( + b_q_weight=qweight, + perm=torch.empty(0, dtype=torch.int, device=device), + size_k=padded_k, + size_n=padded_n, + num_bits=quant_type.size_bits, + ) + s = marlin_pad_scales(s, size_n, size_k, padded_n, padded_k, group_size) + marlin_s = marlin_permute_scales( + s, size_k=padded_k, size_n=padded_n, group_size=group_size + ) + + x = torch.randn(8, size_k, dtype=dtype, device=device) + output = apply_gptq_marlin_linear( + input=x, + weight=marlin_qweight, + weight_scale=marlin_s, + weight_zp=marlin_make_empty_g_idx(device), + g_idx=marlin_make_empty_g_idx(device), + g_idx_sort_indices=marlin_make_empty_g_idx(device), + workspace=marlin_make_workspace_new(device), + wtype=quant_type, + output_size_per_partition=size_n, + input_size_per_partition=size_k, + is_k_full=True, + ) + ref = x @ w_ref + + assert output.shape == (8, size_n) + torch.testing.assert_close(output, ref, rtol=2e-2, atol=2e-2) + + +@pytest.mark.skipif( + _gpu_marlin_unsupported() or not is_fp8_marlin_supported(), + reason="FP8 Marlin is not supported on this GPU type.", +) +@pytest.mark.parametrize("shape", [(200, 512), (4640, 512)]) +def test_fp8_block_marlin_padded_round_trip(shape): + """Block-quantized FP8 (e.g. Nemotron NVFP4 checkpoints' FP8 layers): + group_size=128 exercises the lcm K-alignment in marlin_padded_nk and the + weight_scale_inv group-wise scale padding.""" + size_n, size_k = shape + block = 128 + dtype = torch.float16 + layer = torch.nn.Module() + layer.output_size_per_partition = size_n + layer.input_size_per_partition = size_k + layer.orig_dtype = dtype + layer.weight_block_size = [block, block] + + weight = torch.randn(size_n, size_k, dtype=dtype, device="cuda") / size_k**0.5 + n_blocks, k_blocks = (size_n + block - 1) // block, size_k // block + padded = torch.zeros(n_blocks * block, size_k, dtype=dtype, device="cuda") + padded[:size_n] = weight + scales = padded.view(n_blocks, block, k_blocks, block).abs().amax(dim=(1, 3)) / 448 + scales_expanded = scales.repeat_interleave(block, 0)[:size_n].repeat_interleave( + block, 1 + ) + weight_fp8 = (weight / scales_expanded).to(torch.float8_e4m3fn) + + layer.weight = torch.nn.Parameter(weight_fp8, requires_grad=False) + layer.weight_scale_inv = torch.nn.Parameter( + scales.to(torch.float32), requires_grad=False + ) + + prepare_fp8_layer_for_marlin(layer, size_k_first=False) + + x = torch.randn(8, size_k, dtype=dtype, device="cuda") + output = apply_fp8_marlin_linear( + input=x, + weight=layer.weight, + weight_scale=layer.weight_scale_inv, + workspace=layer.workspace, + size_n=size_n, + size_k=size_k, + bias=None, + ) + ref = x @ (weight_fp8.to(dtype) * scales_expanded.to(dtype)).T + + assert output.shape == (8, size_n) + torch.testing.assert_close(output, ref, rtol=2e-2, atol=2e-2) + + +@pytest.mark.skipif( + _gpu_marlin_unsupported() or not is_fp8_marlin_supported(), + reason="FP8 Marlin is not supported on this GPU type.", +) +@pytest.mark.parametrize("shape", [(200, 288), (4640, 512)]) +def test_mxfp8_marlin_padded_round_trip(shape): + """MXFP8 exercises the e8m0 scale path, where padded 0.0 scales clamp to + 2^-127 instead of zero and must still contribute nothing.""" + size_n, size_k = shape + group_size = 32 + # The e8m0-scale Marlin kernels are only instantiated for bf16 activations. + dtype = torch.bfloat16 + layer = torch.nn.Module() + layer.output_size_per_partition = size_n + layer.input_size_per_partition = size_k + + weight_fp8 = (torch.randn(size_n, size_k, dtype=dtype, device="cuda") / 4).to( + torch.float8_e4m3fn + ) + # e8m0 exponents around 1.0 (127): scales in [2^-6, 2^0] + scales = torch.randint( + 121, 128, (size_n, size_k // group_size), dtype=torch.uint8, device="cuda" + ) + ref_weight = weight_fp8.to(dtype) * ( + 2.0 ** (scales.to(dtype) - 127) + ).repeat_interleave(group_size, 1) + + layer.weight = torch.nn.Parameter(weight_fp8, requires_grad=False) + layer.weight_scale = torch.nn.Parameter(scales, requires_grad=False) + + prepare_mxfp8_layer_for_marlin(layer) + + x = torch.randn(8, size_k, dtype=dtype, device="cuda") / size_k**0.5 + output = apply_mxfp8_marlin_linear( + input=x, + weight=layer.weight, + weight_scale=layer.weight_scale, + workspace=layer.workspace, + size_n=size_n, + size_k=size_k, + ) + ref = x @ ref_weight.T + + assert output.shape == (8, size_n) + torch.testing.assert_close(output, ref, rtol=2e-2, atol=2e-2) + + +@pytest.mark.skipif( + _gpu_marlin_unsupported(), + reason="Marlin is not supported on this GPU type.", +) +@pytest.mark.parametrize("shape", [(200, 512), (4640, 512)]) +def test_awq_zp_marlin_padded_round_trip(shape): + """AWQ-style uint4 with runtime zero-points, padded the way + MarlinLinearKernel does: padded columns rely on (q=0 - zp=0) * scale=0.""" + size_n, size_k = shape + group_size = 128 + dtype = torch.float16 + quant_type = scalar_types.uint4 + device = torch.device("cuda") + + weight = torch.randn(size_k, size_n, dtype=dtype, device=device) / size_k**0.5 + w_ref, q_w, s, zp = quantize_weights( + weight, quant_type, group_size, zero_points=True + ) + qweight = gptq_pack(q_w, quant_type.size_bits, size_k, size_n) + + padded_n, padded_k = marlin_padded_nk(size_n, size_k, group_size) + qweight = marlin_pad_qweight(qweight, size_n, size_k, padded_n, padded_k) + marlin_qweight = ops.gptq_marlin_repack( + b_q_weight=qweight, + perm=torch.empty(0, dtype=torch.int, device=device), + size_k=padded_k, + size_n=padded_n, + num_bits=quant_type.size_bits, + ) + s = marlin_pad_scales(s, size_n, size_k, padded_n, padded_k, group_size) + marlin_s = marlin_permute_scales( + s, size_k=padded_k, size_n=padded_n, group_size=group_size + ) + zp = marlin_pad_scales(zp, size_n, size_k, padded_n, padded_k, group_size) + marlin_zp = marlin_zero_points( + zp, + size_k=padded_k // group_size, + size_n=padded_n, + num_bits=quant_type.size_bits, + ) + + x = torch.randn(8, size_k, dtype=dtype, device=device) + output = apply_gptq_marlin_linear( + input=x, + weight=marlin_qweight, + weight_scale=marlin_s, + weight_zp=marlin_zp, + g_idx=marlin_make_empty_g_idx(device), + g_idx_sort_indices=marlin_make_empty_g_idx(device), + workspace=marlin_make_workspace_new(device), + wtype=quant_type, + output_size_per_partition=size_n, + input_size_per_partition=size_k, + is_k_full=True, + ) + ref = x @ w_ref + + assert output.shape == (8, size_n) + torch.testing.assert_close(output, ref, rtol=2e-2, atol=2e-2) + + +class _FakeLinear: + def __init__(self, size_n, size_k, input_size=None): + self.output_size_per_partition = size_n + self.input_size_per_partition = size_k + self.output_size = size_n + self.input_size = input_size if input_size is not None else size_k + + +def test_check_marlin_supports_layer_allow_tile_padding(): + from vllm.model_executor.layers.quantization.utils.marlin_utils import ( + check_marlin_supports_layer, + ) + + # Tile-misaligned but group-aligned: rejected strictly, allowed w/ padding + layer = _FakeLinear(4640, 512, input_size=2048) + assert not check_marlin_supports_layer(layer, 128) + assert check_marlin_supports_layer(layer, 128, allow_tile_padding=True) + assert check_marlin_supports_layer(layer, -1, allow_tile_padding=True) + + # A group straddling the TP shard cannot be fixed by padding + layer = _FakeLinear(4608, 4672, input_size=18688) + assert not check_marlin_supports_layer(layer, 128, allow_tile_padding=True) diff --git a/tests/kernels/test_flex_attention.py b/tests/kernels/test_flex_attention.py index 41d298134762..86f26cfe8cab 100644 --- a/tests/kernels/test_flex_attention.py +++ b/tests/kernels/test_flex_attention.py @@ -13,6 +13,7 @@ create_standard_kv_cache_spec, create_vllm_config, ) +from vllm.model_executor.layers.attention import Attention from vllm.v1.attention.backends.flex_attention import ( BlockSparsityHint, FlexAttentionMetadataBuilder, @@ -79,6 +80,72 @@ def test_flex_attention_full_cudagraphs(vllm_runner): ) +def windowed_causal_mask_mod(b, h, q_idx, kv_idx): + return (kv_idx <= q_idx) & (q_idx - kv_idx < 4) + + +@pytest.mark.skipif( + not torch.cuda.is_available() or TORCH_VERSION < MINIMUM_TORCH_VERSION, + reason="CUDA not available or PyTorch version < 2.7", +) +def test_flex_attention_custom_mask_full_cudagraphs(vllm_runner, monkeypatch): + monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0") + monkeypatch.setattr( + Attention, + "logical_mask_mod", + staticmethod(windowed_causal_mask_mod), + raising=False, + ) + + model_name = "Qwen/Qwen2.5-1.5B-Instruct" + seed = 42 + max_tokens = 24 + num_logprobs = 5 + prompts = [ + "Hello, my name is", + "The president of the United States is", + "The capital of France is", + ] + + set_random_seed(seed) + with vllm_runner( + model_name, + runner="generate", + tensor_parallel_size=1, + num_gpu_blocks_override=128, + enforce_eager=True, + attention_config={"backend": "FLEX_ATTENTION"}, + ) as llm_eager: + output_eager = llm_eager.generate_greedy_logprobs( + prompts, max_tokens, num_logprobs + ) + + set_random_seed(seed) + with vllm_runner( + model_name, + runner="generate", + tensor_parallel_size=1, + num_gpu_blocks_override=128, + enforce_eager=False, + gpu_memory_utilization=0.85, + compilation_config={ + "cudagraph_mode": "FULL", + "cudagraph_capture_sizes": [4], + }, + attention_config={"backend": "FLEX_ATTENTION"}, + ) as llm_cudagraph: + output_cudagraph = llm_cudagraph.generate_greedy_logprobs( + prompts, max_tokens, num_logprobs + ) + + check_logprobs_close( + outputs_0_lst=output_eager, + outputs_1_lst=output_cudagraph, + name_0="eager", + name_1="cudagraph", + ) + + @pytest.mark.skipif( not torch.cuda.is_available() or TORCH_VERSION < MINIMUM_TORCH_VERSION, reason="CUDA not available or PyTorch version < 2.7", diff --git a/tests/kernels/test_fp32_router_gemm.py b/tests/kernels/test_fp32_router_gemm.py index f855eb7aa171..0673a438c546 100644 --- a/tests/kernels/test_fp32_router_gemm.py +++ b/tests/kernels/test_fp32_router_gemm.py @@ -1,6 +1,9 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Tests for fp32_router_gemm kernel: activation×weight→fp32, H=3072, E=256. +"""Tests for fp32_router_gemm kernel: activation×weight→fp32. + +Supported (hidden_size, num_experts) pairs: + (3072, 256) -> MiniMax-M2/M2.5, (6144, 128) -> MiniMax-M3 Correctness baseline: torch.matmul in float64. """ @@ -10,8 +13,8 @@ from vllm._custom_ops import fp32_router_gemm -NUM_EXPERTS = 256 -HIDDEN_DIM = 3072 +# (hidden_size, num_experts) +SHAPES = [(3072, 256), (6144, 128)] # Absolute tolerance for fp32 kernel vs float64 reference ATOL_FP32 = 2e-4 ATOL_BF16 = 2e-2 # bf16 activation has lower precision @@ -30,49 +33,52 @@ def _ref(mat_a: torch.Tensor, mat_b: torch.Tensor) -> torch.Tensor: return torch.nn.functional.linear(mat_a.float(), mat_b.float()) +@pytest.mark.parametrize("hidden_dim,num_experts", SHAPES) @pytest.mark.parametrize("num_tokens", [1, 2, 4, 8, 16, 32]) -def test_fp32_activation(num_tokens: int): +def test_fp32_activation(num_tokens: int, hidden_dim: int, num_experts: int): """fp32 activation → fp32 output should match reference closely.""" _requires_sm90() torch.manual_seed(42) device = torch.device("cuda") - mat_a = torch.randn(num_tokens, HIDDEN_DIM, dtype=torch.float32, device=device) - mat_b = torch.randn(NUM_EXPERTS, HIDDEN_DIM, dtype=torch.float32, device=device) + mat_a = torch.randn(num_tokens, hidden_dim, dtype=torch.float32, device=device) + mat_b = torch.randn(num_experts, hidden_dim, dtype=torch.float32, device=device) out = fp32_router_gemm(mat_a, mat_b) ref = _ref(mat_a, mat_b) - assert out.shape == (num_tokens, NUM_EXPERTS) + assert out.shape == (num_tokens, num_experts) assert out.dtype == torch.float32 torch.testing.assert_close(out, ref, atol=ATOL_FP32, rtol=0) +@pytest.mark.parametrize("hidden_dim,num_experts", SHAPES) @pytest.mark.parametrize("num_tokens", [1, 2, 4, 8, 16, 32]) -def test_bf16_activation(num_tokens: int): +def test_bf16_activation(num_tokens: int, hidden_dim: int, num_experts: int): """bf16 activation → fp32 output should match reference within bf16 error.""" _requires_sm90() torch.manual_seed(42) device = torch.device("cuda") mat_a_bf16 = torch.randn( - num_tokens, HIDDEN_DIM, dtype=torch.bfloat16, device=device + num_tokens, hidden_dim, dtype=torch.bfloat16, device=device ) - mat_b = torch.randn(NUM_EXPERTS, HIDDEN_DIM, dtype=torch.float32, device=device) + mat_b = torch.randn(num_experts, hidden_dim, dtype=torch.float32, device=device) out = fp32_router_gemm(mat_a_bf16, mat_b) ref = _ref(mat_a_bf16, mat_b).to(device) - assert out.shape == (num_tokens, NUM_EXPERTS) + assert out.shape == (num_tokens, num_experts) assert out.dtype == torch.float32 torch.testing.assert_close(out, ref, atol=ATOL_BF16, rtol=0) -def test_output_shape_and_dtype(): +@pytest.mark.parametrize("hidden_dim,num_experts", SHAPES) +def test_output_shape_and_dtype(hidden_dim: int, num_experts: int): """Basic shape and dtype checks.""" _requires_sm90() device = torch.device("cuda") - mat_a = torch.randn(4, HIDDEN_DIM, dtype=torch.float32, device=device) - mat_b = torch.randn(NUM_EXPERTS, HIDDEN_DIM, dtype=torch.float32, device=device) + mat_a = torch.randn(4, hidden_dim, dtype=torch.float32, device=device) + mat_b = torch.randn(num_experts, hidden_dim, dtype=torch.float32, device=device) out = fp32_router_gemm(mat_a, mat_b) - assert out.shape == (4, NUM_EXPERTS) + assert out.shape == (4, num_experts) assert out.dtype == torch.float32 assert out.device.type == "cuda" diff --git a/tests/kernels/test_fused_minimax_m3_qknorm_rope_kv_insert.py b/tests/kernels/test_fused_minimax_m3_qknorm_rope_kv_insert.py new file mode 100644 index 000000000000..96729614f822 --- /dev/null +++ b/tests/kernels/test_fused_minimax_m3_qknorm_rope_kv_insert.py @@ -0,0 +1,280 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Unit test for the horizontally-fused MiniMax-M3 attention pre-processing +kernel: + + fused_minimax_m3_qknorm_rope_kv_insert + - q / k / index_q / index_k: Gemma RMSNorm + partial NeoX RoPE (in place) + - sparse (insert) mode: scatter k/v into the paged bf16 KV cache and the + index key into the index cache by its own slot mapping. + +Reference: PyTorch Gemma RMSNorm with the same dtype materialization boundary +as the unfused path, followed by vLLM CUDA rotary_embedding-style NeoX RoPE. +""" + +import pytest +import torch + +import vllm._custom_ops as ops + +HEAD_DIM = 128 +ROTARY_DIM = 64 + + +def _op_available() -> bool: + return hasattr(torch.ops._C, "fused_minimax_m3_qknorm_rope_kv_insert") + + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() or not _op_available(), + reason="CUDA not available or fused MiniMax-M3 op not built in", +) + + +def make_cos_sin_cache(max_pos, rotary_dim, base, dtype, device): + inv_freq = 1.0 / ( + base + ** ( + torch.arange(0, rotary_dim, 2, dtype=torch.float32, device=device) + / rotary_dim + ) + ) + t = torch.arange(max_pos, dtype=torch.float32, device=device) + freqs = torch.einsum("i,j->ij", t, inv_freq) # [max_pos, rotary_dim/2] + cache = torch.cat((freqs.cos(), freqs.sin()), dim=-1) # [max_pos, rotary_dim] + return cache.to(dtype) + + +def gemma_rmsnorm(x, weight, eps): + """x: [..., 128]; weight: [128]. Returns original dtype.""" + xf = x.float() + var = xf.pow(2).mean(dim=-1, keepdim=True) + out = xf * torch.rsqrt(var + eps) + out = out * (1.0 + weight.float()) + return out.to(x.dtype) + + +def apply_rope_neox_partial(x, positions, cos_sin_cache, rotary_dim): + """NeoX-style RoPE on the leading rotary_dim dims; rest pass through. + + x: [num_tokens, num_heads, head_dim] + cos_sin_cache: [max_pos, rotary_dim] (cos||sin), read as float (matches the + kernel, which loads the bf16 cache and converts to fp32). + """ + half = rotary_dim // 2 + cs = cos_sin_cache[positions].float() # [num_tokens, rotary_dim] + cos = cs[..., :half].unsqueeze(1) # [nt, 1, half] + sin = cs[..., half:].unsqueeze(1) + + rot = x[..., :rotary_dim].float() + x1 = rot[..., :half] + x2 = rot[..., half:] + o1 = x1 * cos - x2 * sin + o2 = x2 * cos + x1 * sin + out = x.clone() + out[..., :half] = o1 + out[..., half:rotary_dim] = o2 + return out.to(x.dtype) + + +def norm_rope_ref(x, weight, positions, cos_sin_cache, eps): + """[nt, nheads, 128] -> Gemma norm + neox partial rope.""" + normed = gemma_rmsnorm(x, weight, eps) + roped = apply_rope_neox_partial(normed, positions, cos_sin_cache, ROTARY_DIM) + return roped + + +# ── Test 1: dense mode (norm+rope only, no index, no insert) ───────────────── + + +@pytest.mark.parametrize("num_tokens", [1, 7, 64, 513]) +@pytest.mark.parametrize("num_heads,num_kv_heads", [(8, 2), (16, 4), (64, 4)]) +def test_dense_norm_rope(num_tokens, num_heads, num_kv_heads): + torch.manual_seed(0) + device, dtype, eps = "cuda", torch.bfloat16, 1e-6 + base, max_pos = 5_000_000.0, 4096 + + q_w = torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 + k_w = torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 + cos_sin = make_cos_sin_cache(max_pos, ROTARY_DIM, base, dtype, device) + positions = torch.randint( + 0, max_pos, (num_tokens,), dtype=torch.int64, device=device + ) + + qsz, kvsz = num_heads * HEAD_DIM, num_kv_heads * HEAD_DIM + qkv = torch.randn(num_tokens, qsz + 2 * kvsz, dtype=dtype, device=device) + qkv_orig = qkv.clone() + + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv, + q_w, + k_w, + cos_sin, + positions, + num_heads, + num_kv_heads, + ROTARY_DIM, + eps, + kv_cache_dtype="auto", + ) + q_out, k_out, v_out = qkv.split([qsz, kvsz, kvsz], dim=-1) + + q_in, k_in, v_in = qkv_orig.split([qsz, kvsz, kvsz], dim=-1) + q_ref = norm_rope_ref( + q_in.view(num_tokens, num_heads, HEAD_DIM), q_w, positions, cos_sin, eps + ).view(num_tokens, qsz) + k_ref = norm_rope_ref( + k_in.view(num_tokens, num_kv_heads, HEAD_DIM), + k_w, + positions, + cos_sin, + eps, + ).view(num_tokens, kvsz) + + torch.testing.assert_close(q_out, q_ref, rtol=1e-2, atol=1e-2) + torch.testing.assert_close(k_out, k_ref, rtol=1e-2, atol=1e-2) + # V is untouched. + torch.testing.assert_close(v_out, v_in, rtol=0, atol=0) + + +# ── Test 2: sparse mode (full: index branch + cache inserts) ───────────────── + + +@pytest.mark.parametrize("num_tokens", [1, 7, 64, 513]) +@pytest.mark.parametrize("block_size", [16, 64]) +@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"]) +def test_sparse_full(num_tokens, block_size, kv_cache_dtype): + torch.manual_seed(1) + device, dtype, eps = "cuda", torch.bfloat16, 1e-6 + base, max_pos = 5_000_000.0, 4096 + num_heads, num_kv_heads, num_idx_heads = 16, 4, 4 + + q_w = torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 + k_w = torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 + iq_w = torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 + ik_w = torch.randn(HEAD_DIM, dtype=dtype, device=device) * 0.1 + cos_sin = make_cos_sin_cache(max_pos, ROTARY_DIM, base, dtype, device) + positions = torch.randint( + 0, max_pos, (num_tokens,), dtype=torch.int64, device=device + ) + + qsz, kvsz = num_heads * HEAD_DIM, num_kv_heads * HEAD_DIM + iqsz, iksz = num_idx_heads * HEAD_DIM, HEAD_DIM + # Single fused tensor packing [q | k | v | index_q | index_k]. + qkv = torch.randn( + num_tokens, qsz + 2 * kvsz + iqsz + iksz, dtype=dtype, device=device + ) + qkv_orig = qkv.clone() + splits = [qsz, kvsz, kvsz, iqsz, iksz] + + num_blocks = (num_tokens + block_size - 1) // block_size + 1 + kv_cache_storage_dtype = torch.uint8 if kv_cache_dtype == "fp8" else dtype + kv_cache = torch.zeros( + num_blocks, + 2, + block_size, + num_kv_heads, + HEAD_DIM, + dtype=kv_cache_storage_dtype, + device=device, + ) + index_cache = torch.zeros( + num_blocks, block_size, HEAD_DIM, dtype=dtype, device=device + ) + slot_mapping = torch.randperm( + num_blocks * block_size, dtype=torch.int64, device=device + )[:num_tokens] + index_slot_mapping = torch.roll(slot_mapping, shifts=1) + + # Contiguous gather targets: the kernel writes the normed/roped q and + # index_q here (de-interleaved from the packed qkv); k/v/index_k stay in + # place inside qkv and are scatter-inserted into the caches. + q_out = torch.empty(num_tokens, qsz, dtype=dtype, device=device) + index_q = torch.empty(num_tokens, iqsz, dtype=dtype, device=device) + + ops.fused_minimax_m3_qknorm_rope_kv_insert( + qkv, + q_w, + k_w, + cos_sin, + positions, + num_heads, + num_kv_heads, + ROTARY_DIM, + eps, + iq_w, + ik_w, + num_idx_heads, + slot_mapping, + index_slot_mapping, + kv_cache, + index_cache, + block_size, + q_out, + index_q, + kv_cache_dtype, + ) + + # ── norm+rope parity. q/index_q land in their gather buffers; k/index_k are + # rewritten in place inside qkv. ── + _, k_out, v_out, _, index_k = qkv.split(splits, dim=-1) + q_in, k_in, v_in, iq_orig, ik_orig = qkv_orig.split(splits, dim=-1) + q_ref = norm_rope_ref( + q_in.view(num_tokens, num_heads, HEAD_DIM), q_w, positions, cos_sin, eps + ).view(num_tokens, qsz) + k_ref = norm_rope_ref( + k_in.view(num_tokens, num_kv_heads, HEAD_DIM), + k_w, + positions, + cos_sin, + eps, + ).view(num_tokens, kvsz) + iq_ref = norm_rope_ref( + iq_orig.view(num_tokens, num_idx_heads, HEAD_DIM), + iq_w, + positions, + cos_sin, + eps, + ).view(num_tokens, num_idx_heads * HEAD_DIM) + ik_ref = norm_rope_ref( + ik_orig.view(num_tokens, 1, HEAD_DIM), ik_w, positions, cos_sin, eps + ).view(num_tokens, HEAD_DIM) + + torch.testing.assert_close(q_out, q_ref, rtol=1e-2, atol=1e-2) + torch.testing.assert_close(k_out, k_ref, rtol=1e-2, atol=1e-2) + torch.testing.assert_close(index_q, iq_ref, rtol=1e-2, atol=1e-2) + torch.testing.assert_close(index_k, ik_ref, rtol=1e-2, atol=1e-2) + + # ── Cache inserts. ── + # Main cache layout is [num_blocks, 2, block_size, num_kv_heads, head_dim] + # (the K/V axis sits *before* block_size); index cache is [nb, bs, head_dim]. + k_ref_h = k_ref.view(num_tokens, num_kv_heads, HEAD_DIM) + v_ref_h = v_in.view(num_tokens, num_kv_heads, HEAD_DIM) # v is raw (no norm/rope) + if kv_cache_dtype == "fp8": + expected_kv_cache = torch.zeros_like(kv_cache) + scale = torch.ones((), device=device) + ops.reshape_and_cache_flash( + k_out.view(num_tokens, num_kv_heads, HEAD_DIM), + v_out.view(num_tokens, num_kv_heads, HEAD_DIM), + expected_kv_cache[:, 0], + expected_kv_cache[:, 1], + slot_mapping, + kv_cache_dtype, + scale, + scale, + ) + torch.testing.assert_close(kv_cache, expected_kv_cache, rtol=0, atol=0) + else: + for t in range(num_tokens): + s = slot_mapping[t].item() + b, pos = s // block_size, s % block_size + torch.testing.assert_close( + kv_cache[b, 0, pos], k_ref_h[t], rtol=1e-2, atol=1e-2 + ) + torch.testing.assert_close(kv_cache[b, 1, pos], v_ref_h[t], rtol=0, atol=0) + + expected_index_cache = torch.zeros_like(index_cache).view(-1, HEAD_DIM) + expected_index_cache[index_slot_mapping] = index_k + torch.testing.assert_close( + index_cache.view(-1, HEAD_DIM), expected_index_cache, rtol=0, atol=0 + ) diff --git a/tests/kernels/test_minimax_m3_amd_ops.py b/tests/kernels/test_minimax_m3_amd_ops.py new file mode 100644 index 000000000000..9a14edc42713 --- /dev/null +++ b/tests/kernels/test_minimax_m3_amd_ops.py @@ -0,0 +1,337 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Reference-vs-optimized unit tests for the MiniMax-M3 AMD/ROCm fused kernels. + +Each optimized kernel added for the ROCm port has a slow PyTorch reference; the +tests assert the two agree within tolerance: + + * Gemma RMSNorm (plain + fused-add-residual) -> fp32 PyTorch normalize + * SwiGLU-OAI (split layout) -> fp32 PyTorch elementwise + * Fused MXFP8 activation quant (Triton) -> _mxfp8_e4m3_quantize_torch + * Native MXFP8 linear (dot_scaled) -> dequant-to-bf16 @ matmul + * Native MXFP8 MoE (dot_scaled grouped GEMM) -> dequant-to-bf16 MoE math + +The native MXFP8 GEMMs also guard the ``dot_scaled`` rhs-scale orientation: the +scale is loaded ``[N, K//32]`` and passed WITHOUT transpose; a stray ``.T`` +makes the shape ``[K//32, N]`` and Triton raises before producing output, so any +regression there fails these tests loudly. + +Hardware scope: the whole module is ROCm-only (these are the AMD path; NVIDIA +uses the FlashInfer kernels). The norm/activation/quant kernels run on any ROCm +arch; the native MXFP8 ``dot_scaled`` linear/MoE tests are additionally gated to +CDNA4 gfx95x (``@requires_gfx950``) since gfx942 uses the BF16 emulation path. + +Run: pytest tests/kernels/test_minimax_m3_amd_ops.py -v +""" + +import pytest +import torch + +from vllm.platforms import current_platform + +if not current_platform.is_rocm(): + pytest.skip("MiniMax-M3 AMD fused ops require ROCm.", allow_module_level=True) +if not torch.cuda.is_available(): + pytest.skip("Requires a GPU.", allow_module_level=True) + +from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( # noqa: E402 + _mxfp8_e4m3_quantize_torch, + _mxfp8_e4m3_quantize_triton, + dequant_mxfp8_to_bf16, +) +from vllm.models.minimax_m3.amd.ops import ( # noqa: E402 + gemma_fused_add_rmsnorm, + gemma_rmsnorm, + swiglu_oai_split, +) +from vllm.models.minimax_m3.amd.ops.gemma_rmsnorm import _num_warps # noqa: E402 + +DEVICE = "cuda" +EPS = 1e-6 + + +def _gcn_arch() -> str: + try: + return torch.cuda.get_device_properties(0).gcnArchName + except Exception: # pragma: no cover - no device / non-AMD + return "" + + +# The pure-Triton norm/activation/quant kernels run on any ROCm arch (CDNA3 +# gfx942 and CDNA4 gfx950). The native MXFP8 ``dot_scaled`` GEMMs (linear + MoE) +# use CDNA4 hardware microscaling and are gated to gfx95x in the source +# (``RocmDotScaledMxfp8LinearKernel.is_supported``; the MoE oracle routes gfx942 +# to the BF16 emulation path instead) — so those tests are gfx950-only. +requires_gfx950 = pytest.mark.skipif( + "gfx95" not in _gcn_arch(), + reason="native MXFP8 dot_scaled is a CDNA4 (gfx95x) feature; " + "gfx942 uses the BF16 emulation path instead.", +) + + +def _relerr(a: torch.Tensor, b: torch.Tensor) -> float: + a = a.float() + b = b.float() + return ((a - b).norm() / (b.norm() + 1e-8)).item() + + +# --------------------------------------------------------------------------- # +# Gemma RMSNorm +# --------------------------------------------------------------------------- # +def _ref_gemma_rmsnorm(x, w, eps, residual=None): + orig_dtype = x.dtype + xf = x.float() + res_out = None + if residual is not None: + xf = xf + residual.float() + res_out = xf.to(orig_dtype) + xf = xf * torch.rsqrt(xf.pow(2).mean(dim=-1, keepdim=True) + eps) + xf = xf * (1.0 + w.float()) + out = xf.to(orig_dtype) + return out if residual is None else (out, res_out) + + +@pytest.mark.parametrize("shape", [(1, 4096), (37, 6144), (128, 2048)]) +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +@pytest.mark.parametrize("seed", [0, 1234]) +@torch.inference_mode() +def test_gemma_rmsnorm(shape, dtype, seed): + torch.manual_seed(seed) + x = torch.randn(*shape, device=DEVICE, dtype=dtype) + w = torch.randn(shape[-1], device=DEVICE, dtype=dtype) * 0.1 + got = gemma_rmsnorm(x, w, EPS) + ref = _ref_gemma_rmsnorm(x, w, EPS) + assert got.shape == x.shape + assert _relerr(got, ref) < 5e-3 + + +@pytest.mark.parametrize("shape", [(1, 6144), (64, 4096)]) +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +@torch.inference_mode() +def test_gemma_fused_add_rmsnorm(shape, dtype): + torch.manual_seed(0) + x = torch.randn(*shape, device=DEVICE, dtype=dtype) + res = torch.randn(*shape, device=DEVICE, dtype=dtype) + w = torch.randn(shape[-1], device=DEVICE, dtype=dtype) * 0.1 + got_out, got_res = gemma_fused_add_rmsnorm(x, res, w, EPS) + ref_out, ref_res = _ref_gemma_rmsnorm(x, w, EPS, residual=res) + assert _relerr(got_out, ref_out) < 5e-3 + # residual_out is the pre-norm sum (x + res): bit-for-bit identical cast. + assert torch.equal(got_res, ref_res) + + +@torch.inference_mode() +def test_gemma_rmsnorm_per_head_strided(): + """q_norm/k_norm normalize a non-contiguous ``qkv.split`` slice over head_dim.""" + torch.manual_seed(0) + T, H, D, kv = 7, 48, 128, 8 + total = (H + 2 * kv) * D + qkv = torch.randn(T, total, device=DEVICE, dtype=torch.bfloat16) + q = qkv[..., : H * D] # non-contiguous view (row stride == total) + q_by_head = q.view(T, H, D) + assert not q_by_head.is_contiguous() + w = torch.randn(D, device=DEVICE, dtype=torch.bfloat16) * 0.1 + got = gemma_rmsnorm(q_by_head, w, EPS) + ref = _ref_gemma_rmsnorm(q_by_head, w, EPS) + assert got.shape == q_by_head.shape + assert _relerr(got, ref) < 5e-3 + + +def test_num_warps_monotonic(): + assert _num_warps(128) <= _num_warps(2048) <= _num_warps(8192) + + +# --------------------------------------------------------------------------- # +# SwiGLU-OAI (split layout) +# --------------------------------------------------------------------------- # +def _ref_swiglu(gate_up, alpha, beta, limit): + d = gate_up.shape[-1] // 2 + gate = gate_up[..., :d].float() + up = gate_up[..., d:].float() + if limit is not None: + gate = gate.clamp(max=limit) + up = up.clamp(min=-limit, max=limit) + return (gate * torch.sigmoid(alpha * gate) * (up + beta)).to(gate_up.dtype) + + +@pytest.mark.parametrize("m,inter", [(1, 768), (64, 1536), (128, 1024)]) +@pytest.mark.parametrize("limit", [7.0, None]) +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +@torch.inference_mode() +def test_swiglu_oai_split(m, inter, limit, dtype): + torch.manual_seed(0) + gate_up = torch.randn(m, 2 * inter, device=DEVICE, dtype=dtype) + got = swiglu_oai_split(gate_up, alpha=1.702, beta=1.0, limit=limit) + ref = _ref_swiglu(gate_up, 1.702, 1.0, limit) + assert got.shape == (m, inter) + assert _relerr(got, ref) < 5e-3 + + +# --------------------------------------------------------------------------- # +# Fused MXFP8 activation quant (Triton vs torch reference) +# --------------------------------------------------------------------------- # +@pytest.mark.parametrize("shape", [(64, 4096), (1, 6144), (333, 2048)]) +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16]) +@torch.inference_mode() +def test_mxfp8_quant_triton_matches_torch(shape, dtype): + torch.manual_seed(0) + x = torch.randn(*shape, device=DEVICE, dtype=dtype) + xq_t, s_t = _mxfp8_e4m3_quantize_torch(x, is_sf_swizzled_layout=False) + xq_k, s_k = _mxfp8_e4m3_quantize_triton(x) + assert s_k.shape == s_t.shape == (shape[0], shape[1] // 32) + # E8M0 block exponents share the floor(log2(amax))+127 algorithm; allow at + # most a 1-step difference at exact powers of two. + assert (s_k.int() - s_t.int()).abs().max().item() <= 1 + # Dequantized values agree to fp8 granularity. + deq_t = dequant_mxfp8_to_bf16(xq_t, s_t) + deq_k = dequant_mxfp8_to_bf16(xq_k, s_k) + assert _relerr(deq_k, deq_t) < 1e-2 + + +# --------------------------------------------------------------------------- # +# Native MXFP8 linear (dot_scaled) vs dequant-to-bf16 matmul +# --------------------------------------------------------------------------- # +@requires_gfx950 +@pytest.mark.parametrize("m,n,k", [(64, 256, 128), (37, 512, 256), (1, 6144, 4096)]) +@torch.inference_mode() +def test_mxfp8_native_linear(m, n, k): + from vllm.model_executor.kernels.linear.mxfp8.rocm_native import ( + _mxfp8_dot_scaled_linear, + ) + + torch.manual_seed(0) + w_bf16 = torch.randn(n, k, device=DEVICE, dtype=torch.bfloat16) * 0.1 + w_fp8, w_scale = _mxfp8_e4m3_quantize_torch(w_bf16, is_sf_swizzled_layout=False) + x = torch.randn(m, k, device=DEVICE, dtype=torch.bfloat16) * 0.5 + + got = _mxfp8_dot_scaled_linear(x, w_fp8, w_scale) + # Reference: consume the SAME quantized weights (isolates activation-quant + # noise) -> dequant to bf16, plain matmul. + w_deq = dequant_mxfp8_to_bf16(w_fp8, w_scale) + ref = torch.nn.functional.linear(x, w_deq).to(x.dtype) + assert got.shape == (m, n) + # Only the activation is re-quantized inside the kernel -> small MX noise. + assert _relerr(got, ref) < 5e-2 + + +# --------------------------------------------------------------------------- # +# Native MXFP8 MoE (dot_scaled grouped GEMM) vs dequant-to-bf16 MoE math +# --------------------------------------------------------------------------- # +def _ref_moe(x, w13, w2, topk_weights, topk_ids, alpha, beta, limit): + T, H = x.shape + inter = w2.shape[-1] + top_k = topk_ids.shape[1] + out = torch.zeros(T, H, device=x.device, dtype=torch.float32) + for t in range(T): + for j in range(top_k): + e = int(topk_ids[t, j].item()) + g1 = x[t].float() @ w13[e].float().T # [2I] + gate = g1[:inter] + up = g1[inter:] + if limit is not None: + gate = gate.clamp(max=limit) + up = up.clamp(min=-limit, max=limit) + act = gate * torch.sigmoid(alpha * gate) * (up + beta) + g2 = act @ w2[e].float().T # [H] + out[t] += topk_weights[t, j].float() * g2 + return out.to(x.dtype) + + +@requires_gfx950 +@pytest.mark.parametrize( + "T,H,inter,E,top_k", [(8, 256, 512, 8, 2), (1, 512, 256, 16, 4)] +) +@torch.inference_mode() +def test_mxfp8_native_moe(T, H, inter, E, top_k): + from vllm.model_executor.layers.fused_moe.experts.mxfp8_native_moe import ( + fused_moe_mxfp8_native, + ) + + torch.manual_seed(0) + alpha, beta, limit = 1.702, 1.0, 7.0 + w13_bf16 = torch.randn(E, 2 * inter, H, device=DEVICE, dtype=torch.bfloat16) * 0.1 + w2_bf16 = torch.randn(E, H, inter, device=DEVICE, dtype=torch.bfloat16) * 0.1 + w13_fp8, w13_scale = _mxfp8_e4m3_quantize_torch( + w13_bf16, is_sf_swizzled_layout=False + ) + w2_fp8, w2_scale = _mxfp8_e4m3_quantize_torch(w2_bf16, is_sf_swizzled_layout=False) + + x = torch.randn(T, H, device=DEVICE, dtype=torch.bfloat16) * 0.5 + logits = torch.randn(T, E, device=DEVICE, dtype=torch.float32) + topk_weights, topk_ids = logits.softmax(dim=-1).topk(top_k, dim=-1) + topk_weights = topk_weights.to(torch.float32) + topk_ids = topk_ids.to(torch.int32) + + got = fused_moe_mxfp8_native( + x, + w13_fp8, + w13_scale, + w2_fp8, + w2_scale, + topk_weights, + topk_ids, + alpha=alpha, + beta=beta, + limit=limit, + global_num_experts=E, + expert_map=None, + ) + # Reference consumes the dequantized weights (same bits the kernel reads). + w13_deq = dequant_mxfp8_to_bf16(w13_fp8, w13_scale) + w2_deq = dequant_mxfp8_to_bf16(w2_fp8, w2_scale) + ref = _ref_moe(x, w13_deq, w2_deq, topk_weights, topk_ids, alpha, beta, limit) + assert got.shape == (T, H) + assert _relerr(got, ref) < 5e-2 + + +# --------------------------------------------------------------------------- # +# MXFP8 linear emulation: BF16-at-load (default) vs per-step dequant + switch +# --------------------------------------------------------------------------- # +@pytest.mark.parametrize("shape", [(512, 2048), (1, 6144)]) +@pytest.mark.parametrize("act_dtype", [torch.bfloat16, torch.float16]) +@pytest.mark.parametrize("dequant_at_load", [True, False]) +@torch.inference_mode() +def test_mxfp8_linear_emulation_bf16_at_load( + shape, act_dtype, dequant_at_load, monkeypatch +): + """EmulationMxfp8LinearKernel load-time BF16 dequant (default) and the + ``VLLM_MXFP8_EMULATION_DEQUANT_AT_LOAD=0`` per-step fallback must produce the + same result; the dtype-match (BF16/FP16 activations) must also hold.""" + from vllm.model_executor.kernels.linear.mxfp8.emulation import ( + EmulationMxfp8LinearKernel, + ) + from vllm.model_executor.kernels.linear.mxfp8.Mxfp8LinearKernel import ( + Mxfp8LinearLayerConfig, + ) + + monkeypatch.setenv( + "VLLM_MXFP8_EMULATION_DEQUANT_AT_LOAD", "1" if dequant_at_load else "0" + ) + N, K = shape + torch.manual_seed(0) + w_bf16 = torch.randn(N, K, device=DEVICE, dtype=torch.bfloat16) + w_fp8, w_scale = _mxfp8_e4m3_quantize_torch(w_bf16, is_sf_swizzled_layout=False) + assert w_scale.shape == (N, K // 32) + + # Reference: dequant once, plain linear in the activation dtype. + w_ref = dequant_mxfp8_to_bf16(w_fp8, w_scale).to(act_dtype) + x = torch.randn(7, K, device=DEVICE, dtype=act_dtype) + out_ref = torch.nn.functional.linear(x, w_ref) + + layer = torch.nn.Module() + layer.weight = torch.nn.Parameter(w_fp8.clone(), requires_grad=False) + layer.weight_scale = torch.nn.Parameter(w_scale.clone(), requires_grad=False) + + kernel = EmulationMxfp8LinearKernel(Mxfp8LinearLayerConfig()) + kernel.process_weights_after_loading(layer) + + if dequant_at_load: + # weights converted to BF16 at load (>= 2-byte) + assert layer.weight.element_size() >= 2 + else: + # opt-out: weights stay 1-byte MXFP8, dequant happens per-step + assert layer.weight.element_size() == 1 + + out = kernel.apply_weights(layer, x) + assert out.dtype == act_dtype # dtype-match preserved (no tl.dot/F.linear crash) + assert _relerr(out.float(), out_ref.float()) < 2e-2 diff --git a/tests/lora/test_qwen3_with_multi_loras.py b/tests/lora/test_qwen3_with_multi_loras.py index 56bac026b491..0cc8884abafb 100644 --- a/tests/lora/test_qwen3_with_multi_loras.py +++ b/tests/lora/test_qwen3_with_multi_loras.py @@ -6,6 +6,8 @@ 2. test multi loras request """ +import os + import pytest from tests.utils import multi_gpu_test @@ -39,6 +41,18 @@ def format_chatml_messages( ] +@pytest.fixture(autouse=True) +def set_mrv2_env(): + original = os.environ.get("VLLM_USE_V2_MODEL_RUNNER", "0") + os.environ["VLLM_USE_V2_MODEL_RUNNER"] = "1" + yield + + if original is None: + os.environ.pop("VLLM_USE_V2_MODEL_RUNNER", None) + else: + os.environ["VLLM_USE_V2_MODEL_RUNNER"] = original + + def make_add_lora_request(name: str, path: str): global INCREASE_LORA_ID, LORA_NAME_ID_MAP @@ -61,7 +75,6 @@ def test_multi_loras_with_tp_sync(): max_lora_rank=LORA_RANK, max_model_len=512, gpu_memory_utilization=0.5, - enforce_eager=True, tensor_parallel_size=2, # ensure tp >= 2 max_cpu_loras=4, # ensure max_cpu_loras >= 2 ) @@ -167,7 +180,6 @@ def test_multiple_lora_requests(): max_lora_rank=LORA_RANK, max_model_len=512, gpu_memory_utilization=0.5, - enforce_eager=True, ) PROMPTS = ["Hello, my name is"] * 2 LORA_NAME = "Alice" @@ -203,7 +215,6 @@ def test_load_inplace_offline_reload( max_lora_rank=LORA_RANK, max_model_len=512, gpu_memory_utilization=0.5, - enforce_eager=True, ) adapter_id = 1 messages = format_chatml_messages( @@ -254,7 +265,6 @@ def test_load_inplace_false_no_reload( max_lora_rank=LORA_RANK, max_model_len=512, gpu_memory_utilization=0.5, - enforce_eager=True, ) adapter_id = 2 messages = format_chatml_messages( diff --git a/tests/model_executor/model_loader/fastsafetensors_loader/test_weight_utils.py b/tests/model_executor/model_loader/fastsafetensors_loader/test_weight_utils.py index 1975eb61b25d..da974131f65a 100644 --- a/tests/model_executor/model_loader/fastsafetensors_loader/test_weight_utils.py +++ b/tests/model_executor/model_loader/fastsafetensors_loader/test_weight_utils.py @@ -20,7 +20,9 @@ not current_platform.is_cuda_alike(), reason="fastsafetensors requires NVIDIA/AMD GPUs", ) -def test_fastsafetensors_model_loader(): +@pytest.mark.parametrize("queue_size", [0, 1]) +def test_fastsafetensors_model_loader(monkeypatch, queue_size): + monkeypatch.setenv("VLLM_FASTSAFETENSORS_QUEUE_SIZE", str(queue_size)) with tempfile.TemporaryDirectory() as tmpdir: huggingface_hub.constants.HF_HUB_OFFLINE = False download_weights_from_hf( @@ -45,7 +47,3 @@ def test_fastsafetensors_model_loader(): assert fastsafetensors_tensor.dtype == hf_safetensors_tensors[name].dtype assert fastsafetensors_tensor.shape == hf_safetensors_tensors[name].shape assert torch.all(fastsafetensors_tensor.eq(hf_safetensors_tensors[name])) - - -if __name__ == "__main__": - test_fastsafetensors_model_loader() diff --git a/tests/model_executor/model_loader/runai_streamer_loader/test_runai_model_streamer_loader.py b/tests/model_executor/model_loader/runai_streamer_loader/test_runai_model_streamer_loader.py index 82c0f8813e23..e69741556081 100644 --- a/tests/model_executor/model_loader/runai_streamer_loader/test_runai_model_streamer_loader.py +++ b/tests/model_executor/model_loader/runai_streamer_loader/test_runai_model_streamer_loader.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project +import os import types from unittest.mock import patch @@ -78,3 +79,46 @@ def test_runai_passes_revision_by_name(): mock_idx.assert_called_once() assert mock_idx.call_args.kwargs.get("revision") == "myrev" assert "myrev" not in mock_idx.call_args.args + + +def _runai_loader(extra): + return rsl.RunaiModelStreamerLoader( + LoadConfig(load_format="runai_streamer", model_loader_extra_config=extra) + ) + + +@pytest.mark.parametrize( + "extra, match", + [ + ({"typo_key": 1}, "Unexpected extra config"), + ({"distributed": "yes"}, "distributed must be a bool"), + ({"concurrency": "16"}, "concurrency must be a positive integer"), + ({"concurrency": -1}, "concurrency must be a positive integer"), + ], +) +def test_runai_rejects_invalid_extra_config(extra, match): + # The loader used to silently drop unknown keys / wrong types / negatives. + with pytest.raises(ValueError, match=match): + _runai_loader(extra) + + +def test_runai_accepts_valid_extra_config(): + with patch.dict(os.environ, {}, clear=False): + os.environ.pop("RUNAI_STREAMER_CONCURRENCY", None) + os.environ.pop("RUNAI_STREAMER_MEMORY_LIMIT", None) + loader = _runai_loader( + {"distributed": True, "concurrency": 16, "memory_limit": 1024} + ) + assert loader._is_distributed is True + assert os.environ["RUNAI_STREAMER_CONCURRENCY"] == "16" + assert os.environ["RUNAI_STREAMER_MEMORY_LIMIT"] == "1024" + + +def test_runai_invalid_extra_config_leaves_environ_untouched(): + # A later invalid key must not leave an earlier valid key applied to + # os.environ (all values are validated before any global mutation). + with patch.dict(os.environ, {}, clear=False): + os.environ.pop("RUNAI_STREAMER_CONCURRENCY", None) + with pytest.raises(ValueError, match="memory_limit must be a positive integer"): + _runai_loader({"concurrency": 16, "memory_limit": -5}) + assert "RUNAI_STREAMER_CONCURRENCY" not in os.environ diff --git a/tests/model_executor/model_loader/test_registry.py b/tests/model_executor/model_loader/test_registry.py index 020988ccac13..95b797bb5146 100644 --- a/tests/model_executor/model_loader/test_registry.py +++ b/tests/model_executor/model_loader/test_registry.py @@ -8,6 +8,7 @@ from vllm.config.load import LoadConfig from vllm.model_executor.model_loader import get_model_loader, register_model_loader from vllm.model_executor.model_loader.base_loader import BaseModelLoader +from vllm.model_executor.model_loader.default_loader import DefaultModelLoader @register_model_loader("custom_load_format") @@ -33,3 +34,57 @@ def test_invalid_model_loader(): @register_model_loader("invalid_load_format") class InValidModelLoader: pass + + +def test_default_loader_rejects_zero_num_threads(): + # num_threads=0 used to fail late in ThreadPoolExecutor ("max_workers must be > 0"). + with pytest.raises(ValueError, match="num_threads"): + DefaultModelLoader( + LoadConfig( + model_loader_extra_config={ + "enable_multithread_load": True, + "num_threads": 0, + } + ) + ) + + +def test_default_loader_rejects_multithread_with_non_lazy_strategy(): + # The multi-thread loader ignores safetensors_load_strategy; reject the + # combination instead of silently dropping the requested strategy. + with pytest.raises(ValueError, match="does not support"): + DefaultModelLoader( + LoadConfig( + safetensors_load_strategy="torchao", + model_loader_extra_config={"enable_multithread_load": True}, + ) + ) + + +def test_default_loader_explicit_safetensors_does_not_misread_pt(tmp_path): + # Explicit safetensors must not fall back to a .pt and open it as safetensors. + (tmp_path / "model.pt").write_bytes(b"\x00\x00\x00\x00") + loader = DefaultModelLoader(LoadConfig(load_format="safetensors")) + with pytest.raises(RuntimeError, match="Cannot find any model weights"): + loader._prepare_weights( + str(tmp_path), + None, + None, + fall_back_to_pt=True, + allow_patterns_overrides=None, + ) + + +def test_default_loader_hf_still_falls_back_to_pt(tmp_path): + # Control: load_format="hf" still picks up .pt weights via fallback. + (tmp_path / "model.pt").write_bytes(b"\x00\x00\x00\x00") + loader = DefaultModelLoader(LoadConfig(load_format="hf")) + _, files, use_safetensors = loader._prepare_weights( + str(tmp_path), + None, + None, + fall_back_to_pt=True, + allow_patterns_overrides=None, + ) + assert use_safetensors is False + assert any(f.endswith("model.pt") for f in files) diff --git a/tests/model_executor/test_cpu_unquantized_gemm_dispatch.py b/tests/model_executor/test_cpu_unquantized_gemm_dispatch.py index 322897c02468..f18780cf6b57 100644 --- a/tests/model_executor/test_cpu_unquantized_gemm_dispatch.py +++ b/tests/model_executor/test_cpu_unquantized_gemm_dispatch.py @@ -66,3 +66,26 @@ def test_dispatch_cpu_unquantized_gemm_zen_remove_weight(monkeypatch): utils.dispatch_cpu_unquantized_gemm(layer, remove_weight=True) assert layer.weight.numel() == 0 + + +@pytest.mark.usefixtures("_mock_zentorch_linear_unary") +def test_dispatch_cpu_unquantized_gemm_logs_zentorch_dispatch(monkeypatch): + monkeypatch.setattr(current_platform, "is_zen_cpu", lambda: True) + expected_prepacked = bool(utils.envs.VLLM_ZENTORCH_WEIGHT_PREPACK) and hasattr( + torch.ops.zentorch, "zentorch_weight_prepack_for_linear" + ) + + log_calls = [] + monkeypatch.setattr( + utils.logger, "debug_once", lambda *args: log_calls.append(args) + ) + + layer = torch.nn.Linear(16, 8, bias=True) + utils.dispatch_cpu_unquantized_gemm(layer, remove_weight=False) + + assert log_calls == [ + ( + "CPU unquantized GEMM dispatch: using zentorch_linear_unary (prepacked=%s)", + expected_prepacked, + ) + ] diff --git a/tests/models/language/generation/test_common.py b/tests/models/language/generation/test_common.py index a83dff2b3594..1b6c8ef55835 100644 --- a/tests/models/language/generation/test_common.py +++ b/tests/models/language/generation/test_common.py @@ -148,7 +148,11 @@ def test_models( "def add(a, b):\n return a + b\n\ndef sub(a, b):\n return a - " ) - with hf_runner(model) as hf_model: + with hf_runner( + model, + revision=model_info.revision, + trust_remote_code=model_info.trust_remote_code, + ) as hf_model: hf_outputs = hf_model.generate_greedy_logprobs_limit( example_prompts, max_tokens, num_logprobs ) @@ -184,6 +188,7 @@ def test_models( model, tokenizer_name=model_info.tokenizer or model, tokenizer_mode=model_info.tokenizer_mode, + revision=model_info.revision, trust_remote_code=model_info.trust_remote_code, # Remove the effects of batch variance on ROCm since batch invariance # is not yet supported. diff --git a/tests/models/language/generation_ppl_test/ppl_utils.py b/tests/models/language/generation_ppl_test/ppl_utils.py index 59740505e827..2b5449bddcba 100644 --- a/tests/models/language/generation_ppl_test/ppl_utils.py +++ b/tests/models/language/generation_ppl_test/ppl_utils.py @@ -30,7 +30,7 @@ def wikitext_ppl_test( ): vllm_extra_kwargs = get_vllm_extra_kwargs(model_info, vllm_extra_kwargs) - dataset = load_dataset("wikitext", "wikitext-2-raw-v1", split="test") + dataset = load_dataset("Salesforce/wikitext", "wikitext-2-raw-v1", split="test") with vllm_runner( model_info.name, diff --git a/tests/models/multimodal/generation/test_common.py b/tests/models/multimodal/generation/test_common.py index e2dd0d9de76a..a9afe73cad6c 100644 --- a/tests/models/multimodal/generation/test_common.py +++ b/tests/models/multimodal/generation/test_common.py @@ -604,8 +604,6 @@ def _granite4_vision_vllm_to_hf_output(vllm_output, model): models=[ "OpenGVLab/InternVL2-1B", "OpenGVLab/InternVL2-2B", - # FIXME: Config cannot be loaded in transformers 4.52 - # "OpenGVLab/Mono-InternVL-2B", ], test_type=(VLMTestType.IMAGE, VLMTestType.MULTI_IMAGE), prompt_formatter=lambda img_prompt: f"<|im_start|>User\n{img_prompt}<|im_end|>\n<|im_start|>Assistant\n", # noqa: E501 diff --git a/tests/models/multimodal/generation/test_musicflamingo.py b/tests/models/multimodal/generation/test_musicflamingo.py index c87c46a7c3b4..625fbd775d77 100644 --- a/tests/models/multimodal/generation/test_musicflamingo.py +++ b/tests/models/multimodal/generation/test_musicflamingo.py @@ -59,6 +59,12 @@ def get_fixture_path(filename): ) +def load_expected_fixture(filename): + fixture_path = get_fixture_path(filename) + with open(fixture_path) as f: + return json.load(f) + + def assert_output_matches(output, expected_text, expected_token_ids): generated = output.outputs[0] assert generated.text == expected_text @@ -76,7 +82,7 @@ def llm(): model_info.check_transformers_version(on_fail="skip") try: - return LLM( + llm = LLM( model=MODEL_NAME, dtype="bfloat16", enforce_eager=True, @@ -86,14 +92,19 @@ def llm(): except Exception as e: pytest.skip(f"Failed to load model {MODEL_NAME}: {e}") + # ROCm may compile decoder kernels on the first inference pass; warm up + # once so exact fixture assertions cover the steady-state path. + llm.chat( + messages=SINGLE_CONVERSATION, + sampling_params=SamplingParams(temperature=0.0, max_tokens=1), + use_tqdm=False, + ) -def test_single_generation(llm): - fixture_path = get_fixture_path("expected_results_single.json") - if not os.path.exists(fixture_path): - pytest.skip(f"Fixture not found: {fixture_path}") + return llm - with open(fixture_path) as f: - expected = json.load(f) + +def test_single_generation(llm): + expected = load_expected_fixture("expected_results_single.json") outputs = llm.chat( messages=SINGLE_CONVERSATION, @@ -108,12 +119,7 @@ def test_single_generation(llm): def test_batched_generation(llm): - fixture_path = get_fixture_path("expected_results_batched.json") - if not os.path.exists(fixture_path): - pytest.skip(f"Fixture not found: {fixture_path}") - - with open(fixture_path) as f: - expected = json.load(f) + expected = load_expected_fixture("expected_results_batched.json") outputs = llm.chat( messages=BATCHED_CONVERSATIONS, diff --git a/tests/models/multimodal/generation/test_vit_cudagraph.py b/tests/models/multimodal/generation/test_vit_cudagraph.py index a1dc4e5bdd82..52b28ca86008 100644 --- a/tests/models/multimodal/generation/test_vit_cudagraph.py +++ b/tests/models/multimodal/generation/test_vit_cudagraph.py @@ -29,6 +29,7 @@ class VitCudagraphTestConfig: vllm_runner_kwargs: dict = field(default_factory=dict) compilation_config_overrides: dict = field(default_factory=dict) marks: list = field(default_factory=list) + skip: bool = False def params_with_marks( @@ -47,6 +48,13 @@ def internvl_chat_template(content: str) -> str: return f"<|im_start|>user\n{content}<|im_end|>\n<|im_start|>assistant\n" +def kimi_vl_chat_template(content: str) -> str: + return ( + f"<|im_user|>user<|im_middle|>{content}<|im_end|>" + "<|im_assistant|>assistant<|im_middle|>" + ) + + def step3_vl_chat_template(content: str) -> str: return ( "<|begin▁of▁sentence|> You are a helpful assistant.<|BOT|>user\n " @@ -75,15 +83,16 @@ def step3_vl_chat_template(content: str) -> str: }, marks=[pytest.mark.core_model], ), - "internvl": VitCudagraphTestConfig( - model="OpenGVLab/InternVL3-1B", - num_video_frames=8, - image_prompt=internvl_chat_template("\nWhat is in this image?"), - video_prompt=internvl_chat_template( - "