Skip to content

PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度

Enable CUDA CI (#1473)

Sun, Xuehao4f1a8dea0695
diff --git a/.azure-pipelines/scripts/cuda_unit_test/azure_agent.py b/.azure-pipelines/scripts/cuda_unit_test/azure_agent.py
new file mode 100644
index 000000000..851b7ed51
--- /dev/null
+++ b/.azure-pipelines/scripts/cuda_unit_test/azure_agent.py
@@ -0,0 +1,128 @@
+import argparse
+import base64
+import sys
+import time
+
+import requests
+
+API_VERSION = "7.1"
+
+
+def get_auth_header(pat):
+ return {"Authorization": "Basic " + base64.b64encode(f":{pat}".encode()).decode()}
+
+
+def get_pool_id(organization_url, pat, pool_name):
+ url = f"{organization_url}/_apis/distributedtask/pools?poolName={pool_name}&api-version={API_VERSION}"
+ headers = get_auth_header(pat)
+ response = requests.get(url, headers=headers)
+ response.raise_for_status()
+ data = response.json()
+ if data["count"] > 0:
+ return data["value"][0]["id"]
+ return None
+
+
+def wait_for_agent(organization_url, pat, pool_name, agent_name, timeout_seconds=1200):
+ start_time = time.time()
+ sleep_interval = 5
+
+ print(f"Waiting for agent '{agent_name}' to come online in pool '{pool_name}'...")
+
+ pool_id = get_pool_id(organization_url, pat, pool_name)
+ if not pool_id:
+ print(f"Error: Pool '{pool_name}' not found.")
+ sys.exit(1)
+
+ while True:
+ elapsed = time.time() - start_time
+ if elapsed > timeout_seconds:
+ print(f"❌ Timeout: Agent failed to come online within {timeout_seconds} seconds.")
+ sys.exit(1)
+
+ url = f"{organization_url}/_apis/distributedtask/pools/{pool_id}/agents?agentName={agent_name}&api-version={API_VERSION}"
+ headers = get_auth_header(pat)
+ try:
+ response = requests.get(url, headers=headers)
+ response.raise_for_status()
+ data = response.json()
+
+ if data["count"] > 0:
+ agent = data["value"][0]
+ status = agent.get("status")
+ if status == "online":
+ print(f"✅ Agent: {agent_name} is ONLINE and ready!")
+ return
+ else:
+ print(f"⏳ Agent status: '{status}'. Waiting...")
+ else:
+ print(f"⏳ Agent '{agent_name}' not found yet. Waiting...")
+
+ except Exception as e:
+ print(f"⚠️ Error checking agent status: {e}")
+
+ time.sleep(sleep_interval)
+
+
+def deregister_agent(organization_url, pat, pool_name, agent_name):
+ print(f"Attempting to deregister agent '{agent_name}' from pool '{pool_name}'...")
+
+ pool_id = get_pool_id(organization_url, pat, pool_name)
+ if not pool_id:
+ print(f"Pool '{pool_name}' not found. Cannot deregister agent.")
+ return
+
+ url = f"{organization_url}/_apis/distributedtask/pools/{pool_id}/agents?agentName={agent_name}&api-version={API_VERSION}"
+ headers = get_auth_header(pat)
+
+ try:
+ for i in range(5):
+ response = requests.get(url, headers=headers)
+ if response.status_code != 200:
+ print(f"Failed to query agent. Status: {response.status_code}")
+ return
+
+ data = response.json()
+ if data["count"] == 0:
+ if i < 4:
+ print(f"⚠️ Agent: {agent_name} not found in the pool (It might have cleaned itself up). Retrying...")
+ time.sleep(5)
+ continue
+ else:
+ print(f"✅ Agent: {agent_name} not found in the pool (It might have cleaned itself up). Exiting.")
+ return
+
+ agent_id = data["value"][0]["id"]
+ print(f"Found Agent ID: {agent_id}")
+
+ delete_url = (
+ f"{organization_url}/_apis/distributedtask/pools/{pool_id}/agents/{agent_id}?api-version={API_VERSION}"
+ )
+ delete_response = requests.delete(delete_url, headers=headers)
+
+ if delete_response.status_code == 204 or delete_response.status_code == 200:
+ print("✅ Agent successfully removed from Azure DevOps.")
+ else:
+ print(f"❌ Failed to delete agent. Status: {delete_response.status_code}, Response: {delete_response.text}")
+
+ except Exception as e:
+ print(f"Error during deregistration: {e}")
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Manage Azure DevOps Agents")
+ parser.add_argument("--action", required=True, choices=["wait", "deregister"], help="Action to perform")
+ parser.add_argument("--url", required=True, help="Azure DevOps Organization URL (System.CollectionUri)")
+ parser.add_argument("--pat", required=True, help="Azure DevOps PAT")
+ parser.add_argument("--pool", required=True, help="Agent Pool Name")
+ parser.add_argument("--agent", required=True, help="Agent Name")
+
+ args = parser.parse_args()
+
+ if args.action == "wait":
+ wait_for_agent(args.url, args.pat, args.pool, args.agent)
+ elif args.action == "deregister":
+ deregister_agent(args.url, args.pat, args.pool, args.agent)
+ else:
+ print(f"Unknown action: {args.action}")
+ sys.exit(1)
diff --git a/.azure-pipelines/scripts/cuda_unit_test/run_cuda_ut.sh b/.azure-pipelines/scripts/cuda_unit_test/run_cuda_ut.sh
new file mode 100644
index 000000000..70dd09801
--- /dev/null
+++ b/.azure-pipelines/scripts/cuda_unit_test/run_cuda_ut.sh
@@ -0,0 +1,216 @@
+#!/bin/bash
+set -e
+
+PATTERN='[-a-zA-Z0-9_]*='
+
+for i in "$@"; do
+ case $i in
+ --test_case=*)
+ test_case=$(echo $i | sed "s/${PATTERN}//")
+ ;;
+ --test_part=*)
+ test_part=$(echo $i | sed "s/${PATTERN}//")
+ ;;
+ *)
+ echo "Parameter $i not recognized."
+ exit 1
+ ;;
+ esac
+done
+
+source ${BUILD_SOURCESDIRECTORY}/.azure-pipelines/scripts/change_color.sh
+
+LOG_DIR="${BUILD_SOURCESDIRECTORY}/ut_log_dir"
+mkdir -p "${LOG_DIR}"
+SUMMARY_LOG="${LOG_DIR}/results_summary.log"
+
+function setup_environment() {
+ export TZ='Asia/Shanghai'
+ export TQDM_MININTERVAL=120
+ export CUDA_VISIBLE_DEVICES=0
+ export HF_HUB_DISABLE_PROGRESS_BARS=1
+}
+
+function print_summary() {
+ local status=0
+ while IFS= read -r line; do
+ if [[ "$line" == *"FAILED"* ]]; then
+ $LIGHT_RED && echo "$line" && $RESET
+ status=1
+ elif [[ "$line" == *"PASSED"* ]]; then
+ $LIGHT_GREEN && echo "$line" && $RESET
+ elif [[ "$line" == *"NO_TESTS"* ]]; then
+ $LIGHT_YELLOW && echo "$line" && $RESET
+ else
+ echo "$line"
+ fi
+ done < "${SUMMARY_LOG}"
+ exit $status
+}
+
+function check_storage_usage() {
+ echo "##[group]check storage usage..."
+ df -h
+ du -sh "${BUILD_SOURCESDIRECTORY}"
+ du -sh /root/.cache/huggingface
+ du -sh /root/.cache/huggingface/hub/*
+ du -sh /root/.venv
+ echo "##[endgroup]"
+}
+
+function run_unit_test() {
+ # install unit test dependencies
+ echo "##[group]set up UT env..."
+ cd "${BUILD_SOURCESDIRECTORY}" || exit 1
+ uv pip install torch==2.10.0 torchvision
+ uv pip install git+https://github.com/casper-hansen/AutoAWQ.git --no-build-isolation
+
+ # install gptqmodel
+ CUDA_VER=$(python -c 'import torch; print(f"cu{torch.version.cuda.replace(".", "")}")')
+ PY_VER=$(python -c 'import sys; print(f"cp{sys.version_info.major}{sys.version_info.minor}")')
+ TORCH_VER="torch2.10"
+ WHEEL="gptqmodel-5.7.0-${CUDA_VER}${TORCH_VER}-${PY_VER}-${PY_VER}-linux_x86_64.whl"
+ URL="https://pkgs.dev.azure.com/lpot-inc/b7121868-d73a-4794-90c1-23135f974d09/_packaging/4728fbab-e069-4cbd-bcca-d35f4d42256b/pypi/download/gptqmodel/5.7/${WHEEL}"
+ wget -q "$URL" -O "$WHEEL" || { echo "Download failed. Check CUDA/PyTorch/Python versions match (cu126/cu128/cu130, torch2.10, cp310-cp313)"; exit 1; }
+ mv "$WHEEL" "${WHEEL/-${CUDA_VER}${TORCH_VER}-/+${CUDA_VER}.${TORCH_VER}-}"
+ uv pip install "./${WHEEL/-${CUDA_VER}${TORCH_VER}-/+${CUDA_VER}.${TORCH_VER}-}" --no-build-isolation
+ rm -f "./${WHEEL/-${CUDA_VER}${TORCH_VER}-/+${CUDA_VER}.${TORCH_VER}-}"
+
+ uv pip install gptqmodel --extra-index-url https://pkgs.dev.azure.com/lpot-inc/neural-compressor/_packaging/gptqmodel-wheels/pypi/simple/
+ uv pip install -r https://raw.githubusercontent.com/ModelCloud/GPTQModel/refs/tags/v5.7.0/requirements.txt
+ uv pip install https://github.com/XuehaoSun/llama-cpp-python/releases/download/v0.3.16/llama_cpp_python-0.3.16-cp312-cp312-linux_x86_64.whl
+ uv pip install 'git+https://github.com/ggml-org/llama.cpp.git#subdirectory=gguf-py'
+ uv pip install -r test/test_cuda/requirements.txt
+ uv pip install -r test/test_cuda/requirements_diffusion.txt
+ uv pip install -U transformers
+ uv pip install .
+ echo "##[endgroup]"
+
+ uv pip list
+ export COVERAGE_RCFILE="${BUILD_SOURCESDIRECTORY}/.azure-pipelines/scripts/ut/.coverage"
+
+ cd "${BUILD_SOURCESDIRECTORY}/test" || exit 1
+
+ find ./test_cuda -type f -name "test_*.py" | grep -Ev "vlms|llmc|sglang|vllm|multiple_card" | sort > all_tests.txt
+ total_lines=$(wc -l < all_tests.txt)
+ NUM_CHUNKS=2
+ q=$(( total_lines / NUM_CHUNKS ))
+ r=$(( total_lines % NUM_CHUNKS ))
+ if [ "$test_part" -le "$r" ]; then
+ chunk_size=$(( q + 1 ))
+ start_line=$(( (test_part - 1) * chunk_size + 1 ))
+ else
+ chunk_size=$q
+ start_line=$(( r * (q + 1) + (test_part - r - 1) * q + 1 ))
+ fi
+ end_line=$(( start_line + chunk_size - 1 ))
+ selected_files=$(sed -n "${start_line},${end_line}p" all_tests.txt)
+
+ for test_file in ${selected_files}; do
+ echo "##[group]Running ${test_file}..."
+ local test_basename=$(basename ${test_file} .py)
+ local ut_log_name=${LOG_DIR}/unittest_cuda_${test_basename}.log
+
+ pytest -m "not skip_ci" -vs --disable-warnings ${test_file} 2>&1 | tee ${ut_log_name}
+ echo "##[endgroup]"
+ done
+
+ python ${BUILD_SOURCESDIRECTORY}/.azure-pipelines/scripts/ut/collect_result.py --test-type "CUDA Unit Tests" --log-pattern "unittest_cuda_test_*.log" --log-dir ${LOG_DIR} --summary-log ${SUMMARY_LOG}
+}
+
+function run_unit_test_llmc() {
+ echo "##[group]set up UT env..."
+ cd "${BUILD_SOURCESDIRECTORY}" || exit 1
+ rm -rf /root/.venv
+ uv venv --python=3.12 /root/.venv
+ uv pip install -U pytest-cov pytest-html
+ uv pip install -r test/test_cuda/requirements_llmc.txt
+ uv pip install .
+ echo "##[endgroup]"
+ uv pip list
+ cd "${BUILD_SOURCESDIRECTORY}/test" || exit 1
+
+ export COVERAGE_RCFILE="${BUILD_SOURCESDIRECTORY}/.azure-pipelines/scripts/ut/.coverage"
+
+ for test_file in $(find ./test_cuda -name "test_llmc*.py" | sort); do
+ echo "##[group]Running ${test_file}..."
+ local test_basename=$(basename ${test_file} .py)
+ local ut_log_name=${LOG_DIR}/unittest_cuda_llmc_${test_basename}.log
+ pytest -m "not skip_ci" -vs --disable-warnings ${test_file} 2>&1 | tee ${ut_log_name}
+ echo "##[endgroup]"
+ done
+
+ python ${BUILD_SOURCESDIRECTORY}/.azure-pipelines/scripts/ut/collect_result.py --test-type "CUDA LLMC Tests" --log-pattern "unittest_cuda_llmc_test_*.log" --log-dir ${LOG_DIR} --summary-log ${SUMMARY_LOG}
+}
+
+function run_unit_test_sglang() {
+ echo "##[group]set up UT env..."
+ cd "${BUILD_SOURCESDIRECTORY}" || exit 1
+ rm -rf /root/.venv
+ uv venv --python=3.12 /root/.venv
+ uv pip install -U pytest-cov pytest-html
+ uv pip install -r test/test_cuda/requirements_sglang.txt
+ uv pip install .
+ echo "##[endgroup]"
+
+ uv pip list
+ cd "${BUILD_SOURCESDIRECTORY}/test" || exit 1
+ export COVERAGE_RCFILE="${BUILD_SOURCESDIRECTORY}/.azure-pipelines/scripts/ut/.coverage"
+
+ for test_file in $(find ./test_cuda -name "test_sglang*.py" | sort); do
+ echo "##[group]Running ${test_file}..."
+ local test_basename=$(basename ${test_file} .py)
+ local ut_log_name=${LOG_DIR}/unittest_cuda_sglang_${test_basename}.log
+ pytest -m "not skip_ci" -vs --disable-warnings ${test_file} 2>&1 | tee ${ut_log_name}
+ echo "##[endgroup]"
+ done
+
+ python ${BUILD_SOURCESDIRECTORY}/.azure-pipelines/scripts/ut/collect_result.py --test-type "CUDA SGLang Tests" --log-pattern "unittest_cuda_sglang_test_*.log" --log-dir ${LOG_DIR} --summary-log ${SUMMARY_LOG}
+}
+
+function run_unit_test_vllm() {
+ echo "##[group]set up UT env..."
+ cd "${BUILD_SOURCESDIRECTORY}" || exit 1
+ rm -rf /root/.venv
+ uv venv --python=3.12 /root/.venv
+ uv pip install -U pytest-cov pytest-html
+ uv pip install -r test/test_cuda/requirements_vllm.txt
+ uv pip install .
+ echo "##[endgroup]"
+
+ uv pip list
+ cd "${BUILD_SOURCESDIRECTORY}/test" || exit 1
+ export COVERAGE_RCFILE="${BUILD_SOURCESDIRECTORY}/.azure-pipelines/scripts/ut/.coverage"
+
+ for test_file in $(find ./test_cuda -name "test_vllm*.py" | sort); do
+ echo "##[group]Running ${test_file}..."
+ local test_basename=$(basename ${test_file} .py)
+ local ut_log_name=${LOG_DIR}/unittest_cuda_vllm_${test_basename}.log
+ pytest -m "not skip_ci" -vs --disable-warnings ${test_file} 2>&1 | tee ${ut_log_name}
+ echo "##[endgroup]"
+ done
+
+ python ${BUILD_SOURCESDIRECTORY}/.azure-pipelines/scripts/ut/collect_result.py --test-type "CUDA VLLM Tests" --log-pattern "unittest_cuda_vllm_test_*.log" --log-dir ${LOG_DIR} --summary-log ${SUMMARY_LOG}
+}
+
+function main() {
+ setup_environment
+ if [ "${test_case}" == "vlm" ]; then
+ run_unit_test_vlm
+ elif [ "${test_case}" == "llmc" ]; then
+ run_unit_test_llmc
+ elif [ "${test_case}" == "sglang" ]; then
+ run_unit_test_sglang
+ elif [ "${test_case}" == "vllm" ]; then
+ run_unit_test_vllm
+ elif [ "${test_case}" == "all" ]; then
+ run_unit_test
+ else
+ echo "##[error]Invalid test case specified: ${test_case}. Please use 'vlm', 'llmc', 'sglang', 'vllm', or 'all'."
+ exit 1
+ fi
+ check_storage_usage
+ print_summary
+}
+
+main
diff --git a/.azure-pipelines/scripts/cuda_unit_test/runpod_manager.py b/.azure-pipelines/scripts/cuda_unit_test/runpod_manager.py
new file mode 100644
index 000000000..1959433cd
--- /dev/null
+++ b/.azure-pipelines/scripts/cuda_unit_test/runpod_manager.py
@@ -0,0 +1,231 @@
+import argparse
+import json
+import sys
+import time
+
+import requests
+
+TARGET_GPUS = [
+ "NVIDIA GeForce RTX 4090",
+ "NVIDIA RTX PRO 4500 Blackwell",
+ "NVIDIA GeForce RTX 5090",
+ "NVIDIA RTX 6000 Ada Generation",
+ "NVIDIA L40S",
+ "NVIDIA RTX PRO 6000 Blackwell Server Edition",
+]
+REQUIRED_COUNT = 1
+IMAGES_NAME = "xuehaosu/azure-agent:v0.1"
+
+
+def check_gpu_count(token):
+ url = "https://api.runpod.io/graphql"
+ ids_string = ", ".join([f'"{gid}"' for gid in TARGET_GPUS])
+ graphql_query = """
+ query GpuAvailability($input: GpuLowestPriceInput!) {
+ gpuTypes(input: {ids: [%s]}) {
+ id
+ displayName
+ memoryInGb
+ secureCloud
+ communityCloud
+ maxGpuCount
+ maxGpuCountSecureCloud
+ maxGpuCountCommunityCloud
+ minPodGpuCount
+ lowestPrice(input: $input) {
+ gpuName
+ stockStatus
+ minimumBidPrice
+ uninterruptablePrice
+ maxGpuCount
+ maxUnreservedGpuCount
+ availableGpuCounts
+ rentedCount
+ totalCount
+ }
+ }
+ }
+ """ % ids_string
+ variables = {"input": {"gpuCount": 1, "secureCloud": True, "minMemoryInGb": 0, "minVcpuCount": 0}}
+
+ try:
+ response = requests.post(
+ url,
+ json={
+ "query": graphql_query,
+ "variables": variables,
+ },
+ headers={
+ "Content-Type": "application/json",
+ "Authorization": f"Bearer {token}",
+ },
+ )
+ response.raise_for_status()
+ data = response.json()
+ all_gpus = data.get("data", {}).get("gpuTypes", [])
+
+ id_to_gpu = {gpu["id"]: gpu for gpu in all_gpus}
+ all_gpus = [id_to_gpu[gpu_id] for gpu_id in TARGET_GPUS if gpu_id in id_to_gpu]
+
+ print("--- Checking target graphics card inventory ---\n")
+
+ for gpu in all_gpus:
+ gpu_id = gpu.get("id")
+
+ if gpu_id in TARGET_GPUS:
+ max_count = gpu.get("lowestPrice", {}).get("maxUnreservedGpuCount", 0)
+
+ if REQUIRED_COUNT > max_count:
+ continue
+ else:
+ return gpu_id
+
+ print("❌ No compliant GPU found.")
+ return None
+
+ except requests.exceptions.RequestException as e:
+ print(f"HTTP Error: {e}")
+ sys.exit(1)
+ except Exception as e:
+ print(f"Error: {e}")
+ sys.exit(1)
+
+
+def run_create_pod(api_key, payload):
+ url = "https://rest.runpod.io/v1/pods"
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
+ response = requests.post(url, json=payload, headers=headers)
+
+ response.raise_for_status()
+ result = response.json()
+ if "errors" in result:
+ print("❌ Errors:")
+ print(json.dumps(result["errors"], indent=2))
+ sys.exit(1)
+ return result
+
+
+def create_pod(args):
+ if args.env:
+ env_dict = {kv.split("=", 1)[0]: kv.split("=", 1)[1] for kv in args.env}
+
+ gpu_type = None
+ for _ in range(10): # Try up to 10 times to find an available GPU
+ gpu_type = check_gpu_count(args.api_key)
+ if gpu_type:
+ break
+ else:
+ print("⏳ No compliant GPU available. Retrying in 5 minutes...")
+ time.sleep(60 * 5)
+
+ if not gpu_type:
+ print("❌ No compliant GPU found after multiple attempts. Exiting.")
+ sys.exit(1)
+
+ payload = {
+ "cloudType": "SECURE",
+ "containerDiskInGb": args.container_disk_size,
+ "env": env_dict,
+ "gpuCount": args.gpu_count,
+ "gpuTypeIds": [gpu_type],
+ "name": args.name,
+ "volumeInGb": 0,
+ "imageName": IMAGES_NAME,
+ }
+
+ print(f"🚀 Creating pod: {args.name}...")
+ data = run_create_pod(args.api_key, payload)
+ if data:
+ pod_id = data.get("id")
+ if pod_id:
+ print(f"✅ Pod created successfully! Pod ID: {pod_id}")
+ print(f" Status is: {data.get('desiredStatus')}")
+ else:
+ print("❌ Failed to create pod (no data returned).")
+ sys.exit(1)
+
+
+def get_pod_id(args):
+ url = f"https://rest.runpod.io/v1/pods?name={args.name}"
+ headers = {"Authorization": "Bearer " + args.api_key}
+ try:
+ response = requests.get(url, headers=headers)
+ response.raise_for_status()
+ data = response.json()[0] if response.json() else None
+ if data:
+ print(f"Pod status: {data.get('desiredStatus', 'unknown')}")
+ if data and "id" in data:
+ return data["id"]
+
+ print(f"⚠️ Pod '{args.name}' not found.")
+ return None
+
+ except Exception as e:
+ print(f"⚠️ Error fetching pods: {e}")
+ raise e
+
+
+def wait_for_pod(args):
+ for _ in range(60): # Wait up to 10 minutes
+ pod_id = get_pod_id(args)
+ if pod_id:
+ print(f"✅ Pod '{args.name}' is now available with ID: {pod_id}")
+ return
+ else:
+ print(f"⏳ Waiting for pod '{args.name}' to be created...")
+ time.sleep(10)
+ print(f"❌ Timeout: Pod '{args.name}' was not created within the expected time.")
+ sys.exit(1)
+
+
+def terminate_pod(args):
+ pod_id = args.pod_id or get_pod_id(args)
+ if not pod_id:
+ get_pod_id(args) # Just to check if pod exists and print status
+ sys.exit(1)
+
+ url = f"https://rest.runpod.io/v1/pods/{pod_id}"
+ headers = {"Authorization": f"Bearer {args.api_key}"}
+ response = requests.delete(url, headers=headers)
+ response.raise_for_status()
+
+ max_tries = 30
+
+ for i in range(max_tries): # Wait up to 5 minutes for termination
+ pod_id = get_pod_id(args)
+ if pod_id:
+ print(f"⚠️ Pod {args.name}: {pod_id} termination initiated, but pod still exists")
+ if i >= max_tries - 1:
+ raise Exception(
+ f"❌ Pod {args.name}: {pod_id} termination may not have completed yet. Please check the status."
+ )
+ else:
+ print(f"✅ Pod {args.name} termination command sent.")
+ break
+ time.sleep(10) # Wait a bit for termination to process
+
+
+def main():
+ parser = argparse.ArgumentParser(description="RunPod Pod Manager via API")
+ parser.add_argument("--action", choices=["create", "terminate", "wait"], required=True)
+ parser.add_argument("--api_key", required=True)
+ parser.add_argument("--pod_id", help="Pod ID for termination")
+ parser.add_argument("--name", help="Pod name")
+ parser.add_argument("--gpu_count", type=int, default=1)
+ parser.add_argument("--container_disk_size", type=int, default=50)
+ parser.add_argument("--part", type=int, default=0)
+ parser.add_argument("--env", nargs="*", help="Environment variables in KEY=VALUE format")
+
+ args = parser.parse_args()
+
+ if args.action == "create":
+ time.sleep(args.part * 15)
+ create_pod(args)
+ elif args.action == "terminate":
+ terminate_pod(args)
+ elif args.action == "wait":
+ wait_for_pod(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.azure-pipelines/scripts/ut/collect_result.py b/.azure-pipelines/scripts/ut/collect_result.py
new file mode 100644
index 000000000..63a4c46b1
--- /dev/null
+++ b/.azure-pipelines/scripts/ut/collect_result.py
@@ -0,0 +1,234 @@
+"""Log analyzer for test results with summary generation."""
+
+import argparse
+import re
+import sys
+from collections import deque
+from dataclasses import dataclass
+from enum import Enum, auto
+from pathlib import Path
+
+
+class TestStatus(Enum):
+ """Test execution status."""
+
+ PASSED = auto()
+ FAILED = auto()
+ NO_TESTS = auto()
+
+
+@dataclass(frozen=True)
+class TestResult:
+ """Represents a single test result."""
+
+ name: str
+ status: TestStatus
+ filename: str
+ duration: str
+
+
+class LogAnalyzer:
+ """Analyzes test log files and generates summary reports."""
+
+ TIME_PATTERN = re.compile(r"in\s+([\d.]+)s")
+ PREFIX_PATTERNS = (
+ "unittest_cuda_vlm_",
+ "unittest_cuda_vllm_",
+ "unittest_cuda_sglang_",
+ "unittest_cuda_llmc_",
+ "unittest_cuda_",
+ "unittest_",
+ )
+
+ FAILURE_MARKERS = (
+ "FAILED",
+ "== FAILURES ==",
+ " failures",
+ "Killed",
+ "AssertionError",
+ "Error:",
+ "core dumped",
+ )
+
+ ERROR_MARKERS = (
+ "ERROR",
+ "== ERRORS ==",
+ " errors",
+ "Exception",
+ "Traceback",
+ )
+
+ PASS_MARKER = " passed"
+
+ def __init__(self, log_dir: Path, log_pattern: str = "*.log"):
+ self.log_dir = Path(log_dir)
+ self.log_pattern = log_pattern
+
+ def analyze_all(self) -> list[TestResult]:
+ """Analyze all matching log files and return sorted results."""
+ search_path = self.log_dir / self.log_pattern
+ print(f"Searching: {search_path}", file=sys.stderr)
+
+ log_files = sorted(self.log_dir.glob(self.log_pattern))
+ print(f"Found {len(log_files)} files", file=sys.stderr)
+
+ results = []
+ for log_file in log_files:
+ if log_file.is_file():
+ result = self._analyze_single(log_file)
+ results.append(result)
+ return results
+
+ def _analyze_single(self, log_file: Path) -> TestResult:
+ content = self._read_log(log_file)
+ return TestResult(
+ name=self._extract_test_name(log_file),
+ status=self._determine_status(content),
+ filename=log_file.name,
+ duration=self._extract_duration(content),
+ )
+
+ def _read_log(self, path: Path, max_lines: int = 100) -> str:
+ try:
+ with open(path, "r", encoding="utf-8", errors="ignore") as f:
+ return "".join(deque(f, maxlen=max_lines))
+ except OSError as e:
+ print(f"Warning: Cannot read {path} - {e}", file=sys.stderr)
+ return ""
+
+ def _extract_test_name(self, path: Path) -> str:
+ name = path.stem
+ for prefix in self.PREFIX_PATTERNS:
+ if name.startswith(prefix):
+ return name[len(prefix) :]
+ return name
+
+ def _determine_status(self, content: str) -> TestStatus:
+ """Determine test status from log content."""
+ if any(marker in content for marker in self.FAILURE_MARKERS):
+ return TestStatus.FAILED
+ if any(marker in content for marker in self.ERROR_MARKERS):
+ return TestStatus.FAILED
+ if self.PASS_MARKER in content:
+ return TestStatus.PASSED
+ return TestStatus.NO_TESTS
+
+ def _extract_duration(self, content: str) -> str:
+ if match := self.TIME_PATTERN.search(content):
+ total_seconds = int(float(match.group(1)))
+ hours, remainder = divmod(total_seconds, 3600)
+ minutes, seconds = divmod(remainder, 60)
+ return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
+ return "00:00:00"
+
+
+class ReportGenerator:
+ """Generates formatted test summary reports."""
+
+ WIDTHS = {"name": 35, "status": 10, "file": 50, "time": 10}
+ SEPARATOR = "=" * 120
+
+ def __init__(self, output_path: Path):
+ self.output_path = Path(output_path)
+
+ def generate(self, test_type: str, results: list[TestResult]) -> None:
+ """Generate and APPEND summary report to file."""
+ if not results:
+ print("No results to write", file=sys.stderr)
+ return
+
+ stats = self._calculate_stats(results)
+
+ lines = [
+ "",
+ self.SEPARATOR,
+ f"Test Results Summary - {test_type}",
+ self.SEPARATOR,
+ self._format_header(),
+ self._format_subheader(),
+ *(self._format_row(r) for r in results),
+ self.SEPARATOR,
+ f"Total: {stats['total']}, Passed: {stats['passed']}, "
+ f"Failed: {stats['failed']}, Skipped: {stats['skipped']}",
+ self.SEPARATOR,
+ "",
+ ]
+
+ with open(self.output_path, "a", encoding="utf-8") as f:
+ f.write("\n".join(lines))
+
+ print(f"Summary appended to: {self.output_path.absolute()}", file=sys.stderr)
+
+ def _calculate_stats(self, results: list[TestResult]) -> dict[str, int]:
+ total = len(results)
+ passed = sum(1 for r in results if r.status == TestStatus.PASSED)
+ failed = sum(1 for r in results if r.status == TestStatus.FAILED)
+ return {
+ "total": total,
+ "passed": passed,
+ "failed": failed,
+ "skipped": total - passed - failed,
+ }
+
+ def _format_header(self) -> str:
+ return (
+ f"{'Test Case':<{self.WIDTHS['name']}} "
+ f"{'Result':<{self.WIDTHS['status']}} "
+ f"{'Log File':<{self.WIDTHS['file']}} "
+ f"{'Time':<{self.WIDTHS['time']}}"
+ )
+
+ def _format_subheader(self) -> str:
+ return (
+ f"{'-' * 10:<{self.WIDTHS['name']}} "
+ f"{'-' * 6:<{self.WIDTHS['status']}} "
+ f"{'-' * 8:<{self.WIDTHS['file']}} "
+ f"{'-' * 4:<{self.WIDTHS['time']}}"
+ )
+
+ def _format_row(self, result: TestResult) -> str:
+ return (
+ f"{result.name:<{self.WIDTHS['name']}} "
+ f"{result.status.name:<{self.WIDTHS['status']}} "
+ f"{result.filename:<{self.WIDTHS['file']}} "
+ f"{result.duration:<{self.WIDTHS['time']}}"
+ )
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Analyze test logs and generate summary")
+ parser.add_argument("--test-type", required=True, help="Type of tests")
+ parser.add_argument("--log-dir", required=True, type=Path, help="Directory with logs")
+ parser.add_argument("--summary-log", required=True, type=Path, help="Output file")
+ parser.add_argument("--log-pattern", default="*.log", help="Glob pattern")
+
+ args = parser.parse_args()
+
+ if not args.log_dir.exists():
+ print(f"Error: Directory not found: {args.log_dir}", file=sys.stderr)
+ sys.exit(1)
+
+ try:
+ analyzer = LogAnalyzer(args.log_dir, args.log_pattern)
+ results = analyzer.analyze_all()
+
+ reporter = ReportGenerator(args.summary_log)
+ reporter.generate(args.test_type, results)
+
+ stats = {
+ "total": len(results),
+ "passed": sum(1 for r in results if r.status == TestStatus.PASSED),
+ "failed": sum(1 for r in results if r.status == TestStatus.FAILED),
+ }
+ print(f"Done: {stats['total']} tests, {stats['passed']} passed, {stats['failed']} failed")
+
+ except Exception as e:
+ print(f"Error: {e}", file=sys.stderr)
+ import traceback
+
+ traceback.print_exc(file=sys.stderr)
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.azure-pipelines/scripts/ut/run_ut.sh b/.azure-pipelines/scripts/ut/run_ut.sh
index bad1e5c7e..2a0134e8c 100644
--- a/.azure-pipelines/scripts/ut/run_ut.sh
+++ b/.azure-pipelines/scripts/ut/run_ut.sh
@@ -1,64 +1,137 @@
#!/bin/bash
-set -xe
+set -e
test_part=$1
-export TQDM_MININTERVAL=60
-export HF_HUB_DISABLE_PROGRESS_BARS=1
-echo "##[group]set up UT env..."
-uv pip install pytest-cov pytest-html
-uv pip list
-# workaround for ark test, remove auto_round_kernel_xpu
-package_path=$(uv pip show auto-round-lib | grep Location:|cut -d: -f2)
-rm -rf $package_path/auto_round_kernel/auto_round_kernel_xpu*
-echo "##[endgroup]"
-# install latest gguf for ut test
-cd ~ || exit 1
-git clone -b master --quiet --single-branch https://github.com/ggml-org/llama.cpp.git && cd llama.cpp/gguf-py && uv pip install . sentencepiece
+source /auto-round/.azure-pipelines/scripts/change_color.sh
-cd /auto-round && uv pip install .
+LOG_DIR=/auto-round/log_dir
+mkdir -p "${LOG_DIR}"
+SUMMARY_LOG="${LOG_DIR}/results_summary.log"
-echo "##[endgroup]"
-uv pip list
+function setup_environment() {
+ echo "##[group]set up UT env..."
+ export TZ='Asia/Shanghai'
+ export TQDM_MININTERVAL=120
+ export HF_HUB_DISABLE_PROGRESS_BARS=1
-rm -rf /auto-round/auto_round
-cd /auto-round/test || exit 1
+ uv pip install pytest-cov pytest-html
+ uv pip list
+ # workaround for ark test, remove auto_round_kernel_xpu
+ package_path=$(uv pip show auto-round-lib | grep Location:|cut -d: -f2)
+ rm -rf $package_path/auto_round_kernel/auto_round_kernel_xpu*
-export LD_LIBRARY_PATH=${HOME}/.venv/lib/:$LD_LIBRARY_PATH
-export FORCE_BF16=1
-export COVERAGE_RCFILE=/auto-round/.azure-pipelines/scripts/ut/.coverage
-auto_round_path=$(python -c 'import auto_round; print(auto_round.__path__[0])')
+ # install latest gguf for ut test
+ cd ~ || exit 1
+ git clone -b master --quiet --single-branch https://github.com/ggml-org/llama.cpp.git && cd llama.cpp/gguf-py && uv pip install . sentencepiece
-LOG_DIR=/auto-round/log_dir
-mkdir -p ${LOG_DIR}
-ut_log_name=${LOG_DIR}/ut.log
-
-# Split test files into 5 parts
-find ./test_cpu -name "test*.py" | sort > all_tests.txt
-total_lines=$(wc -l < all_tests.txt)
-NUM_CHUNKS=5
-q=$(( total_lines / NUM_CHUNKS ))
-r=$(( total_lines % NUM_CHUNKS ))
-if [ "$test_part" -le "$r" ]; then
- chunk_size=$(( q + 1 ))
- start_line=$(( (test_part - 1) * chunk_size + 1 ))
-else
- chunk_size=$q
- start_line=$(( r * (q + 1) + (test_part - r - 1) * q + 1 ))
-fi
-end_line=$(( start_line + chunk_size - 1 ))
-selected_files=$(sed -n "${start_line},${end_line}p" all_tests.txt)
-printf '%s\n' "${selected_files}" | sed "s,\.\/,python -m pytest --cov=\"${auto_round_path}\" --cov-report term --html=report.html --self-contained-html --cov-report xml:coverage.xml --cov-append -vs --disable-warnings ,g" > run.sh
-cat run.sh
-numactl --physcpubind="${NUMA_CPUSET:-0-15}" --membind="${NUMA_NODE:-0}" bash run.sh 2>&1 | tee "${ut_log_name}"
-
-if [ $(grep -c '== FAILURES ==' ${ut_log_name}) != 0 ] || [ $(grep -c '== ERRORS ==' ${ut_log_name}) != 0 ] || \
-[ $(grep -c 'Killed' ${ut_log_name}) != 0 ] || [ $(grep -c 'core dumped' ${ut_log_name}) != 0 ] || [ $(grep -c ' passed' ${ut_log_name}) == 0 ]; then
- echo "##[error]Find errors in pytest case, please check the output..."
- exit 1
-fi
-
-# if ut pass, collect the coverage file into artifacts
-cp .coverage "${LOG_DIR}/.coverage.part${test_part}"
-
-echo "UT finished successfully! "
+ cd /auto-round && uv pip install .
+
+ export LD_LIBRARY_PATH=${HOME}/.venv/lib/:$LD_LIBRARY_PATH
+ export FORCE_BF16=1
+ export COVERAGE_RCFILE=/auto-round/.azure-pipelines/scripts/ut/.coverage
+ echo "##[endgroup]"
+
+ uv pip list
+}
+
+function print_summary() {
+ local status=0
+ while IFS= read -r line; do
+ if [[ "$line" == *"FAILED"* ]]; then
+ $LIGHT_RED && echo "$line" && $RESET
+ status=1
+ elif [[ "$line" == *"PASSED"* ]]; then
+ $LIGHT_GREEN && echo "$line" && $RESET
+ elif [[ "$line" == *"NO_TESTS"* ]]; then
+ $LIGHT_YELLOW && echo "$line" && $RESET
+ else
+ echo "$line"
+ fi
+ done < "${SUMMARY_LOG}"
+ exit $status
+}
+
+function check_storage_usage() {
+ echo "##[group]check storage usage..."
+ df -h
+ du -sh /auto-round
+ du -sh /home/hostuser/.cache/huggingface
+ du -sh /home/hostuser/.cache/huggingface/hub/*
+ du -sh /home/hostuser/.venv
+ echo "##[endgroup]"
+}
+
+function run_unit_test() {
+ cd /auto-round/test || exit 1
+ auto_round_path=$(python -c 'import auto_round; print(auto_round.__path__[0])')
+
+ # Split test files into 5 parts
+ find ./test_cpu -name "test*.py" | grep -Ev "llmc" | sort > all_tests.txt
+ total_lines=$(wc -l < all_tests.txt)
+ NUM_CHUNKS=5
+ q=$(( total_lines / NUM_CHUNKS ))
+ r=$(( total_lines % NUM_CHUNKS ))
+ if [ "$test_part" -le "$r" ]; then
+ chunk_size=$(( q + 1 ))
+ start_line=$(( (test_part - 1) * chunk_size + 1 ))
+ else
+ chunk_size=$q
+ start_line=$(( r * (q + 1) + (test_part - r - 1) * q + 1 ))
+ fi
+ end_line=$(( start_line + chunk_size - 1 ))
+ selected_files=$(sed -n "${start_line},${end_line}p" all_tests.txt)
+
+ for test_file in ${selected_files}; do
+ echo "##[group]Running ${test_file}..."
+ local test_basename=$(basename ${test_file} .py)
+ local ut_log_name=${LOG_DIR}/unittest_${test_basename}.log
+
+ numactl --physcpubind="${NUMA_CPUSET:-0-15}" --membind="${NUMA_NODE:-0}" \
+ python -m pytest --cov="${auto_round_path}" --cov-report term --html=report.html --self-contained-html \
+ --cov-report xml:coverage.xml --cov-append \
+ -vs --disable-warnings ${test_file} 2>&1 | tee ${ut_log_name}
+ echo "##[endgroup]"
+ done
+}
+
+function run_llmc_unit_test() {
+ uv pip install -r /auto-round/test/test_cpu/requirements_llmc.txt
+ uv pip uninstall auto-round
+ cd /auto-round && uv pip install .
+
+ cd /auto-round/test || exit 1
+ auto_round_path=$(python -c 'import auto_round; print(auto_round.__path__[0])')
+
+ for test_file in $(find ./test_cpu -name "test_llmc*.py" | sort); do
+ echo "##[group]Running ${test_file}..."
+ local test_basename=$(basename ${test_file} .py)
+ local ut_log_name=${LOG_DIR}/unittest_${test_basename}.log
+
+ numactl --physcpubind="${NUMA_CPUSET:-0-15}" --membind="${NUMA_NODE:-0}" \
+ python -m pytest --cov="${auto_round_path}" --cov-report term --html=report.html --self-contained-html \
+ --cov-report xml:coverage.xml --cov-append \
+ -vs --disable-warnings ${test_file} 2>&1 | tee ${ut_log_name}
+ echo "##[endgroup]"
+ done
+}
+
+function collect_log() {
+ python /auto-round/.azure-pipelines/scripts/ut/collect_result.py \
+ --test-type "Unit Tests" --log-pattern "unittest_test_*.log" --log-dir ${LOG_DIR} --summary-log ${SUMMARY_LOG}
+
+ cp .coverage "${LOG_DIR}/.coverage.part${test_part}"
+}
+
+function main() {
+ setup_environment
+ run_unit_test
+ if [ "$test_part" -eq 5 ]; then
+ run_llmc_unit_test
+ fi
+ collect_log
+ check_storage_usage
+ print_summary
+}
+
+main
diff --git a/.azure-pipelines/scripts/ut/run_ut_cuda.sh b/.azure-pipelines/scripts/ut/run_ut_cuda.sh
index bab846abb..aeb236733 100644
--- a/.azure-pipelines/scripts/ut/run_ut_cuda.sh
+++ b/.azure-pipelines/scripts/ut/run_ut_cuda.sh
@@ -107,7 +107,7 @@ function run_unit_test() {
local auto_round_path=$(python -c 'import auto_round; print(auto_round.__path__[0])')
# run unit tests individually with separate logs
- for test_file in $(find ./test_cuda -name "test_*.py" ! -name "test_*vlms.py" ! -name "test_llmc*.py" ! -name "test_*sglang*.py" | sort); do
+ for test_file in $(find ./test_cuda -type f -name "test_*.py" | grep -Ev "vlms|llmc|sglang|vllm|multiple_card" | sort); do
local test_basename=$(basename ${test_file} .py)
local ut_log_name=${LOG_DIR}/unittest_cuda_${test_basename}.log
echo "Running ${test_file}..."
@@ -231,7 +231,40 @@ function run_unit_test_sglang() {
fi
}
+function run_unit_test_vllm() {
+ # install unit test dependencies
+ create_conda_env
+
+ cd ${REPO_PATH}/test
+ rm -rf .coverage* *.xml *.html
+ uv pip install -r test_cuda/requirements_vllm.txt
+ cd ${REPO_PATH} && uv pip install . && cd ${REPO_PATH}/test
+
+ pip list > ${LOG_DIR}/vllm_ut_pip_list.txt
+ export COVERAGE_RCFILE=${REPO_PATH}/.azure-pipelines/scripts/ut/.coverage
+ local auto_round_path=$(python -c 'import auto_round; print(auto_round.__path__[0])')
+
+ # run unit tests individually with separate logs
+ for test_file in $(find ./test_cuda -name "test_vllm*.py" | sort); do
+ local test_basename=$(basename ${test_file} .py)
+ local ut_log_name=${LOG_DIR}/unittest_cuda_vllm_${test_basename}.log
+ echo "Running ${test_file}..."
+
+ python -m pytest --cov="${auto_round_path}" --cov-report term --html=report_vllm.html --self-contained-html --cov-report xml:coverage_vllm.xml --cov-append -vs --disable-warnings ${test_file} 2>&1 | tee ${ut_log_name}
+ done
+
+ if [ -f "report_vllm.html" ] && [ -f "coverage_vllm.xml" ]; then
+ mv report_vllm.html ${LOG_DIR}/
+ mv coverage_vllm.xml ${LOG_DIR}/
+ fi
+ # Print test results table and check for failures
+ if ! print_test_results_table "unittest_cuda_vllm_test*.log" "CUDA VLLM Unit Tests"; then
+ echo "Some CUDA VLLM unit tests failed. Please check the individual log files for details."
+ fi
+}
+
function main() {
+ run_unit_test_vllm
run_unit_test_vlm
run_unit_test_llmc
run_unit_test_sglang
diff --git a/.azure-pipelines/unit-test-cuda.yml b/.azure-pipelines/unit-test-cuda.yml
new file mode 100644
index 000000000..8c0a77341
--- /dev/null
+++ b/.azure-pipelines/unit-test-cuda.yml
@@ -0,0 +1,212 @@
+trigger: none
+
+pr:
+ autoCancel: true
+ drafts: false
+ branches:
+ include:
+ - main
+ paths:
+ include:
+ - auto_round
+ - auto_round_extension
+ - test/test_cuda
+ - setup.py
+ - requirements.txt
+ - .azure-pipelines/scripts/cuda_unit_test
+ - .azure-pipelines/unit-test-cuda.yml
+
+ exclude:
+ - "*.md"
+ - "**/*.md"
+
+variables:
+ - name: POOL_NAME
+ value: "RunPod-GPU-Pool"
+ - name: AGENT_NAME
+ value: "runpod-agent-$(Build.BuildId)"
+
+parameters:
+ - name: matrix
+ type: object
+ default:
+ part0:
+ PART: 0
+ part1:
+ PART: 1
+ part2:
+ PART: 2
+
+stages:
+ - ${{ each pair in parameters.matrix }}:
+ - stage: Start_Pod_${{ pair.key }}
+ displayName: "Start Pod ${{ pair.value.PART }}"
+ dependsOn: []
+ jobs:
+ - job: Start_Pod_Job
+ displayName: "Launch Pod & Run CUDA Tests"
+ timeoutInMinutes: 60
+ pool:
+ vmImage: "ubuntu-latest"
+ steps:
+ - checkout: self
+
+ - task: UsePythonVersion@0
+ inputs:
+ versionSpec: "3.13"
+ displayName: "Use Python 3.13"
+
+ - task: Bash@3
+ displayName: "Install dependencies"
+ inputs:
+ targetType: "inline"
+ script: |
+ pip install requests
+
+ - task: Bash@3
+ displayName: "Create RunPod Instance"
+ name: create_runpod
+ inputs:
+ targetType: "inline"
+ script: |
+ export PYTHONUNBUFFERED=1
+ cd ${BUILD_SOURCESDIRECTORY}
+ python .azure-pipelines/scripts/cuda_unit_test/runpod_manager.py \
+ --action create \
+ --api_key $(RUNPOD_API_KEY) \
+ --name "ci-$(Build.BuildId)-${{ pair.value.PART }}" \
+ --container_disk_size "100" \
+ --part ${{ pair.value.PART }} \
+ --env AZP_URL=$(System.CollectionUri) AZP_TOKEN=$(AZP_DEVOPS_PAT) AZP_POOL=$(POOL_NAME) AZP_AGENT_NAME="$(AGENT_NAME)-part${{ pair.value.PART }}"
+
+ - task: Bash@3
+ displayName: "Wait for Pod to be Online"
+ name: wait_for_pod
+ inputs:
+ targetType: "inline"
+ script: |
+ cd ${BUILD_SOURCESDIRECTORY}
+ export PYTHONUNBUFFERED=1
+ python .azure-pipelines/scripts/cuda_unit_test/runpod_manager.py \
+ --action wait \
+ --api_key $(RUNPOD_API_KEY) \
+ --name "ci-$(Build.BuildId)-${{ pair.value.PART }}"
+
+ - task: Bash@3
+ displayName: "Wait for Agent to be Online"
+ name: wait_for_agent
+ inputs:
+ targetType: "inline"
+ script: |
+ cd ${BUILD_SOURCESDIRECTORY}
+ export PYTHONUNBUFFERED=1
+ python .azure-pipelines/scripts/cuda_unit_test/azure_agent.py \
+ --action wait \
+ --url "$(System.CollectionUri)" \
+ --pat "$(AZP_DEVOPS_PAT)" \
+ --pool "$(POOL_NAME)" \
+ --agent "$(AGENT_NAME)-part${{ pair.value.PART }}"
+
+ - stage: GPU_Test_${{ pair.key }}
+ displayName: "GPU Test ${{ pair.value.PART }}"
+ dependsOn: Start_Pod_${{ pair.key }}
+ jobs:
+ - job: GpuTests
+ timeoutInMinutes: 60
+ pool:
+ name: "$(POOL_NAME)"
+ demands: Agent.Name -equals runpod-agent-$(Build.BuildId)-part${{ pair.value.PART }}
+ steps:
+ - checkout: self
+ clean: true
+ displayName: "Checkout Repo"
+
+ - script: |
+ echo "Running on GPU Agent: $(Agent.Name)"
+ nvidia-smi
+ lscpu
+ displayName: "Verify GPU Access"
+
+ - script: |
+ echo "##[group]Installing Python dependencies..."
+ uv pip install -U "pytest-cov" "pytest-html" "requests" "huggingface_hub"
+ hf auth login --token "$(HF_TOKEN)"
+ echo "##[endgroup]"
+ displayName: "Install Python Dependencies"
+
+ - script: |
+ if [ ${{ pair.value.PART }} -eq 0 ]; then
+ export UV_NO_CACHE=0
+ bash .azure-pipelines/scripts/cuda_unit_test/run_cuda_ut.sh \
+ --test_case=sglang
+ bash .azure-pipelines/scripts/cuda_unit_test/run_cuda_ut.sh \
+ --test_case=llmc
+ bash .azure-pipelines/scripts/cuda_unit_test/run_cuda_ut.sh \
+ --test_case=vllm
+ else
+ bash .azure-pipelines/scripts/cuda_unit_test/run_cuda_ut.sh \
+ --test_case=all \
+ --test_part=${{ pair.value.PART }}
+ fi
+ displayName: "Run GPU Tests"
+
+ - task: PublishPipelineArtifact@1
+ condition: succeededOrFailed()
+ inputs:
+ targetPath: $(Build.SourcesDirectory)/ut_log_dir
+ artifact: PART_${{ pair.value.PART }}_logs
+ publishLocation: "pipeline"
+
+ - stage: Cleanup_Verification_${{ pair.key }}
+ displayName: "Verify Pod Cleanup ${{ pair.value.PART }}"
+ dependsOn:
+ - Start_Pod_${{ pair.key }}
+ - GPU_Test_${{ pair.key }}
+ condition: always()
+ jobs:
+ - job: Verify_Cleanup
+ pool:
+ vmImage: "ubuntu-latest"
+ steps:
+ - checkout: self
+
+ - task: UsePythonVersion@0
+ inputs:
+ versionSpec: "3.13"
+ displayName: "Use Python 3.13"
+
+ - task: Bash@3
+ displayName: "Install dependencies"
+ condition: always()
+ inputs:
+ targetType: "inline"
+ script: |
+ pip install requests
+
+ - task: Bash@3
+ displayName: "Terminate RunPod Instance"
+ condition: always()
+ inputs:
+ targetType: "inline"
+ script: |
+ echo "Terminating Pod: ci-$(Build.BuildId)-${{ pair.value.PART }}"
+ export PYTHONUNBUFFERED=1
+ python .azure-pipelines/scripts/cuda_unit_test/runpod_manager.py \
+ --action terminate \
+ --api_key $(RUNPOD_API_KEY) \
+ --name "ci-$(Build.BuildId)-${{ pair.value.PART }}"
+
+ - task: Bash@3
+ displayName: "Deregister Agent from Pool"
+ condition: always()
+ inputs:
+ targetType: "inline"
+ script: |
+ cd ${BUILD_SOURCESDIRECTORY}
+ export PYTHONUNBUFFERED=1
+ python .azure-pipelines/scripts/cuda_unit_test/azure_agent.py \
+ --action deregister \
+ --url "$(System.CollectionUri)" \
+ --pat "$(AZP_DEVOPS_PAT)" \
+ --pool "$(POOL_NAME)" \
+ --agent "$(AGENT_NAME)-part${{ pair.value.PART }}"
diff --git a/.azure-pipelines/unit-test-hpu.yml b/.azure-pipelines/unit-test-hpu.yml
index 917d368c4..34fb65ece 100644
--- a/.azure-pipelines/unit-test-hpu.yml
+++ b/.azure-pipelines/unit-test-hpu.yml
@@ -13,7 +13,7 @@ pr:
- test/test_hpu
- setup.py
- requirements-hpu.txt
- - .azure-pipelines/scripts/ut
+ - .azure-pipelines/scripts/ut/run_ut_hpu.sh
- .azure-pipelines/template/docker-template.yml
- .azure-pipelines/template/ut-template.yml
exclude:
@@ -21,8 +21,6 @@ pr:
- auto_round/export/export_to_awq
- "*.md"
- "**/*.md"
- - .azure-pipelines/scripts/ut/run_ut_cuda.sh
- - .azure-pipelines/scripts/ut/run_ut.sh
pool: GAUDI
diff --git a/.azure-pipelines/unit-test-xpu.yml b/.azure-pipelines/unit-test-xpu.yml
index 5214021ee..adb04bf27 100644
--- a/.azure-pipelines/unit-test-xpu.yml
+++ b/.azure-pipelines/unit-test-xpu.yml
@@ -16,6 +16,7 @@ pr:
- .azure-pipelines/template/ut-template.yml
- .azure-pipelines/unit-test-xpu.yml
- .azure-pipelines/scripts/ut/run_ut_xpu.sh
+ - .azure-pipelines/docker/Dockerfile_xpu.devel
exclude:
- "*.md"
- "**/*.md"
diff --git a/.azure-pipelines/unit-test.yml b/.azure-pipelines/unit-test.yml
index ec4e7e2e3..9c5da664e 100644
--- a/.azure-pipelines/unit-test.yml
+++ b/.azure-pipelines/unit-test.yml
@@ -23,6 +23,7 @@ pr:
- test/test_hpu
- test/test_ark
- test/test_xpu
+ - test/test_cuda
- "*.md"
- "**/*.md"
- .azure-pipelines/scripts/ut/run_ut_hpu.sh
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 9b966be05..174e75b0f 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -34,6 +34,11 @@ repos:
hooks:
- id: black
files: (.*\.py)$
+ exclude: |
+ (?x)^(
+ .azure-pipelines/scripts/cuda_unit_test/.+
+ )$
+
- repo: https://github.com/asottile/blacken-docs
rev: 1.20.0
diff --git a/auto_round/export/utils.py b/auto_round/export/utils.py
index df8ebd37a..69531e8de 100644
--- a/auto_round/export/utils.py
+++ b/auto_round/export/utils.py
@@ -63,10 +63,15 @@ def save_model(
model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
try:
- copy_missing_tensors_from_source(
- source_dir=model.config._name_or_path,
- target_dir=save_dir,
- )
+ if (
+ hasattr(model, "config")
+ and hasattr(model.config, "_name_or_path")
+ and model.config.name_or_path is not None # set None for tiny model
+ ):
+ copy_missing_tensors_from_source(
+ source_dir=model.config._name_or_path,
+ target_dir=save_dir,
+ )
except Exception as e:
logger.warning("Skipping copy of missing tensors from source checkpoint due to error: %s", e)
@@ -84,7 +89,12 @@ def save_model(
json.dump(model.config.quantization_config, f, indent=2)
try:
- copy_python_files_from_model_cache(model, save_dir)
+ if (
+ hasattr(model, "config")
+ and hasattr(model.config, "_name_or_path")
+ and model.config.name_or_path is not None # set None for tiny model
+ ):
+ copy_python_files_from_model_cache(model, save_dir)
except Exception as e:
logger.warning("Skipping source model Python file copy due to error: %s", e)
diff --git a/auto_round/utils/common.py b/auto_round/utils/common.py
index 0a699ef84..177a4266b 100644
--- a/auto_round/utils/common.py
+++ b/auto_round/utils/common.py
@@ -665,23 +665,20 @@ def json_serialize(obj: Any):
def get_reciprocal(tensor):
"""
Memory-frugal reciprocal:
- - Inplace operations on original tensor
- - Only allocates small boolean mask
+ - Uses torch.where to avoid boolean indexing (aten.nonzero),
+ which is not supported by torch.compile inductor backend.
"""
eps = 1e-5 if tensor.dtype == torch.float16 else 1e-30
- # Create mask for very small elements (small overhead)
- mask = tensor.abs() < eps
+ # Create mask for very small elements
+ safe = tensor.abs() >= eps
- # Prepare output in place: reuse tensor if allowed, otherwise create once
- recip = torch.empty_like(tensor)
-
- # Safe reciprocal: for nonzero elements
- nonzero_mask = ~mask
- recip[nonzero_mask] = 1.0 / tensor[nonzero_mask]
-
- # Zero out elements below threshold
- recip[mask] = 0.0
+ # Use torch.where to avoid graph breaks under torch.compile
+ # Replace near-zero values with 1.0 before dividing to avoid inf,
+ # then mask the result. Both branches are evaluated by torch.where,
+ # so the dummy 1.0 prevents division-by-zero in the unsafe branch.
+ safe_tensor = torch.where(safe, tensor, torch.ones_like(tensor))
+ recip = torch.where(safe, 1.0 / safe_tensor, torch.zeros_like(tensor))
return recip
diff --git a/pyproject.toml b/pyproject.toml
index 9249c6ad4..99ffdaa8c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -18,7 +18,8 @@ line-length = 120
[tool.typos]
[tool.typos.files]
extend-exclude = [
- ".azure-pipelines/scripts/codeScan/codespell/autoround_dict.txt"
+ ".azure-pipelines/scripts/codeScan/codespell/autoround_dict.txt",
+ ".azure-pipelines/scripts/cuda_unit_test/runpod_manager.py"
]
[tool.typos.default.extend-words]
ue = "ue"
diff --git a/test/conftest.py b/test/conftest.py
index d21100824..5a500ed3d 100644
--- a/test/conftest.py
+++ b/test/conftest.py
@@ -9,6 +9,19 @@ from .fixtures import *
# Easy debugging without installing auto-round.
sys.path.insert(0, "..")
+# Workaround: some gguf builds report version 'N/A' which is not PEP 440
+# compliant and causes packaging.version.InvalidVersion inside transformers.
+try:
+ import gguf as _gguf_mod
+ from packaging.version import Version
+
+ try:
+ Version(_gguf_mod.__version__)
+ except Exception:
+ _gguf_mod.__version__ = "0.0.0"
+except ImportError:
+ pass
+
### HPU related configuration, usage: `pytest --mode=compile/lazy``
def pytest_addoption(parser):
diff --git a/test/fixtures.py b/test/fixtures.py
index 624ee1a19..b2a4068c5 100644
--- a/test/fixtures.py
+++ b/test/fixtures.py
@@ -1,5 +1,6 @@
import os
import shutil
+from unittest.mock import patch
import datasets
import pytest
@@ -10,6 +11,7 @@ from .helpers import (
DataLoader,
deepseek_v2_name_or_path,
gemma_name_or_path,
+ get_model_path,
get_tiny_model,
gptj_name_or_path,
lamini_name_or_path,
@@ -89,6 +91,18 @@ def tiny_qwen_model_path():
shutil.rmtree(tiny_model_path, ignore_errors=True)
[email protected](scope="session")
+def tiny_fp8_qwen_model_path():
+ from unittest.mock import patch
+
+ with patch("torch.cuda.get_device_capability", return_value=(9, 0)):
+ model_name_or_path = get_model_path("Qwen/Qwen3-0.6B-FP8")
+ tiny_model_path = "./tmp/tiny_fp8_qwen_model_path"
+ tiny_model_path = save_tiny_model(model_name_or_path, tiny_model_path)
+ yield tiny_model_path
+ shutil.rmtree(tiny_model_path, ignore_errors=True)
+
+
@pytest.fixture(scope="session")
def tiny_untied_qwen_model_path():
model_name_or_path = qwen_name_or_path
@@ -111,7 +125,7 @@ def tiny_qwen_moe_model_path():
def tiny_qwen_vl_model_path():
model_name_or_path = qwen_vl_name_or_path
tiny_model_path = "./tmp/tiny_qwen_vl_model_path"
- tiny_model_path = save_tiny_model(model_name_or_path, tiny_model_path, num_layers=2, is_mllm=True)
+ tiny_model_path = save_tiny_model(model_name_or_path, tiny_model_path, num_layers=3, is_mllm=True)
yield tiny_model_path
shutil.rmtree(tiny_model_path, ignore_errors=True)
@@ -125,6 +139,148 @@ def tiny_qwen_2_5_vl_model_path():
shutil.rmtree(tiny_model_path, ignore_errors=True)
[email protected](scope="session")
+def tiny_fp8_qwen_moe_model_path():
+ with patch("torch.cuda.get_device_capability", return_value=(9, 0)):
+ tiny_model_path = "./tmp/tiny_fp8_qwen_moe_model_path"
+ model_name = get_model_path("Qwen/Qwen3-30B-A3B-FP8")
+ config = transformers.AutoConfig.from_pretrained(model_name, trust_remote_code=True)
+ config.num_experts, config.num_hidden_layers, config.vocab_size = 4, 2, 2048
+ model = transformers.AutoModelForCausalLM.from_config(config, trust_remote_code=True)
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_name)
+ from transformers.integrations.finegrained_fp8 import FP8Expert, FP8Linear
+
+ for name, module in model.named_modules():
+ if name == "lm_head":
+ continue
+ if "mlp.gate" in name:
+ continue
+ if isinstance(module, torch.nn.Linear):
+ fp8_linear = FP8Linear(
+ module.in_features,
+ module.out_features,
+ bias=module.bias is not None,
+ block_size=[128, 128],
+ )
+ model.set_submodule(name, fp8_linear)
+ if name.endswith("mlp.experts"):
+ fp8_expert = FP8Expert(
+ config=model.config.get_text_config(),
+ block_size=[128, 128],
+ )
+ model.set_submodule(name, fp8_expert)
+
+ model.save_pretrained(tiny_model_path)
+ print(model)
+ tokenizer.save_pretrained(tiny_model_path)
+ yield tiny_model_path
+ shutil.rmtree(tiny_model_path, ignore_errors=True)
+
+
[email protected](scope="session")
+def tiny_gpt_oss_model_path():
+ tiny_model_path = "./tmp/tiny_gpt_oss"
+ from transformers import GptOssForCausalLM
+
+ model_name = get_model_path("unsloth/gpt-oss-20b")
+ config = transformers.AutoConfig.from_pretrained(model_name, trust_remote_code=True)
+ config.num_hidden_layers = 1 # Reduce layers for testing
+ config.layer_types = config.layer_types[:1] # Keep only the first layer type for testing
+ delattr(config, "quantization_config")
+ model = GptOssForCausalLM(config)
+ model.save_pretrained(tiny_model_path)
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
+ tokenizer.save_pretrained(tiny_model_path)
+ yield tiny_model_path
+ shutil.rmtree(tiny_model_path, ignore_errors=True)
+
+
[email protected](scope="session")
+def tiny_llama4_model_path():
+ tiny_model_path = "./tmp/tiny_llama4"
+ from transformers import Llama4ForConditionalGeneration
+
+ model_name = get_model_path("meta-llama/Llama-4-Scout-17B-16E-Instruct")
+ config = transformers.AutoConfig.from_pretrained(model_name, trust_remote_code=True)
+ # TODO: Remove after https://github.com/huggingface/transformers/issues/43525 is resolved
+ config.pad_token_id = None
+ config.vision_config.num_hidden_layers = 1 # Reduce layers for testing
+ config.text_config.num_hidden_layers = 1
+ config.text_config.num_hidden_layers = 1
+ model = Llama4ForConditionalGeneration(config)
+ # Remove these parameters to avoid mismatch during quantized model loading
+ model.config.text_config.no_rope_layers = []
+ if hasattr(model.config.text_config, "moe_layers"):
+ delattr(model.config.text_config, "moe_layers")
+ if hasattr(model.config.text_config, "layer_types"):
+ delattr(model.config.text_config, "layer_types")
+ model.save_pretrained(tiny_model_path)
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
+ tokenizer.save_pretrained(tiny_model_path)
+ processor = transformers.AutoProcessor.from_pretrained(model_name, trust_remote_code=True)
+ processor.save_pretrained(tiny_model_path)
+ yield tiny_model_path
+ shutil.rmtree(tiny_model_path, ignore_errors=True)
+
+
[email protected](scope="session")
+def tiny_qwen3_vl_moe_model_path():
+ tiny_model_path = "./tmp/tiny_qwen3_vl_moe"
+ from transformers.models.qwen3_vl_moe.modeling_qwen3_vl_moe import Qwen3VLMoeForConditionalGeneration
+
+ model_name = get_model_path("Qwen/Qwen3-VL-30B-A3B-Instruct")
+ config = transformers.AutoConfig.from_pretrained(model_name)
+ config.vision_config.depth = 1 # Reduce layers for testing
+ config.text_config.num_hidden_layers = 1
+ config.text_config.num_experts = 16
+ config.num_hidden_layers = 1
+ model = Qwen3VLMoeForConditionalGeneration(config)
+ model.save_pretrained(tiny_model_path)
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_name)
+ tokenizer.save_pretrained(tiny_model_path)
+ processor = transformers.AutoProcessor.from_pretrained(model_name)
+ processor.save_pretrained(tiny_model_path)
+ yield tiny_model_path
+ shutil.rmtree(tiny_model_path, ignore_errors=True)
+
+
[email protected](scope="session")
+def tiny_qwen35_moe_model_path():
+ tiny_model_path = "./tmp/tiny_qwen35_moe"
+ from transformers import Qwen3_5MoeForConditionalGeneration
+
+ model_name = get_model_path("Qwen/Qwen3.5-35B-A3B")
+ config = transformers.AutoConfig.from_pretrained(model_name)
+ config.text_config.pad_token_id = None
+ config.vision_config.depth = 1 # Reduce layers for testing
+ config.text_config.num_hidden_layers = 4
+ config.num_hidden_layers = 1
+ config.text_config.layer_types = config.text_config.layer_types[: config.text_config.num_hidden_layers]
+ config.text_config.use_cache = False
+ model = Qwen3_5MoeForConditionalGeneration(config)
+ model.save_pretrained(tiny_model_path)
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_name)
+ tokenizer.save_pretrained(tiny_model_path)
+ processor = transformers.AutoProcessor.from_pretrained(model_name)
+ processor.save_pretrained(tiny_model_path)
+ yield tiny_model_path
+ shutil.rmtree(tiny_model_path, ignore_errors=True)
+
+
[email protected](scope="session")
+def tiny_tiny_llama_model_path():
+ tiny_model_path = "./tmp/tiny_TinyLlama"
+ model_name = get_model_path("TinyLlama/TinyLlama-1.1B-Chat-v1.0")
+ config = transformers.AutoConfig.from_pretrained(model_name)
+ config.num_hidden_layers = 4
+ model = transformers.AutoModelForCausalLM.from_config(config)
+ model.save_pretrained(tiny_model_path)
+ tokenizer = transformers.AutoTokenizer.from_pretrained(model_name)
+ tokenizer.save_pretrained(tiny_model_path)
+ yield tiny_model_path
+ shutil.rmtree(tiny_model_path, ignore_errors=True)
+
+
@pytest.fixture(scope="session")
def tiny_qwen2_5_omni():
"""Tiny Qwen2.5-Omni-3B model built from real config with reduced layers.
@@ -155,6 +311,7 @@ def tiny_qwen2_5_omni():
config.talker_config.layer_types = config.talker_config.layer_types[:1]
model = Qwen2_5OmniForConditionalGeneration(config)
+ model.config.name_or_path = None
yield model, tokenizer, processor
@@ -191,6 +348,7 @@ def tiny_qwen3_omni_moe():
config.talker_config.num_hidden_layers = 1
model = Qwen3OmniMoeForConditionalGeneration(config)
+ model.config.name_or_path = None
yield model, tokenizer, processor
diff --git a/test/helpers.py b/test/helpers.py
index 8a5d24649..040fdf82d 100644
--- a/test/helpers.py
+++ b/test/helpers.py
@@ -9,16 +9,16 @@ import transformers
from packaging import version
from auto_round.eval.evaluation import simple_evaluate, simple_evaluate_user_model
-from auto_round.utils import get_attr, llm_load_model, mllm_load_model, set_attr
+from auto_round.utils import detect_device, get_attr, llm_load_model, mllm_load_model, set_attr
transformers_version = version.parse(transformers.__version__)
-def generate_prompt(model, tokenizer, text="There is a girl who likes adventure,", max_new_tokens=50):
+def generate_prompt(model_obj_or_str, tokenizer=None, text="The capital of France is,", max_new_tokens=10, device=None):
"""Generate text using a model and tokenizer.
Args:
- model: The model to use for generation.
+ model_obj_or_str: The model to use for generation.
tokenizer: The tokenizer for the model.
text: The input prompt text.
max_new_tokens: Maximum number of new tokens to generate.
@@ -26,12 +26,31 @@ def generate_prompt(model, tokenizer, text="There is a girl who likes adventure,
Returns:
str: The generated text.
"""
+ if device is None:
+ device = detect_device()
+ if isinstance(model_obj_or_str, str):
+ model, tokenizer = llm_load_model(model_obj_or_str, trust_remote_code=True)
+ else:
+ model = model_obj_or_str
+ assert tokenizer is not None, "Tokenizer must be provided when model is a model object"
+ if not (hasattr(model, "hf_device_map") and len(model.hf_device_map) > 1):
+ model = model.to(device)
inputs = tokenizer(text, return_tensors="pt").to(model.device)
- output = tokenizer.decode(model.generate(**inputs, max_new_tokens=max_new_tokens)[0])
+ generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens)[0]
+ output = tokenizer.decode(generated_ids)
print(output)
return output
+def eval_generated_prompt(
+ model, tokenizer=None, prompt_text="The United States of", target_text="America", max_new_tokens=10, device=None
+):
+ """Evaluate the generated text using a model and tokenizer."""
+ out = generate_prompt(model, tokenizer, text=prompt_text, max_new_tokens=max_new_tokens, device=device)
+ assert target_text.lower() in out.lower(), f"Expected '{target_text}' in output, but got: {out}"
+ return out
+
+
def evaluate_accuracy(
model_or_save_dir, tokenizer=None, task="lambada_openai", threshold=0.25, batch_size="auto", limit=None
):
@@ -76,6 +95,7 @@ def get_model_path(model_name: str) -> str:
model_name = model_name.rstrip("/")
ut_path = f"/tf_dataset/auto_round/models/{model_name}"
local_path = f"/models/{model_name.split('/')[-1]}"
+ local_path_1 = f"/dataset/{model_name.split('/')[-1]}"
if "DeepSeek-V2-Lite" in model_name and os.path.exists("/data0/deepseek-ai/DeepSeek-V2-Lite"):
return "/data0/deepseek-ai/DeepSeek-V2-Lite"
@@ -84,10 +104,47 @@ def get_model_path(model_name: str) -> str:
return ut_path
elif os.path.exists(local_path):
return local_path
+ elif os.path.exists(local_path_1):
+ return local_path_1
else:
return model_name
+def get_captions_dataset_path() -> str:
+ """Find captions_source.tsv locally or download it to tmp.
+
+ Checks /dataset/, /tf_dataset/, and test/tmp/ for the file.
+ If not found, downloads from the mlcommons URL to test/tmp/.
+
+ Returns:
+ str: The path to captions_source.tsv.
+ """
+ import urllib.request
+
+ filename = "captions_source.tsv"
+ url = (
+ "https://raw.githubusercontent.com/mlcommons/inference/refs/heads/master/"
+ "text_to_image/coco2014/captions/captions_source.tsv"
+ )
+
+ local_candidates = [
+ f"/dataset/{filename}",
+ f"/tf_dataset/{filename}",
+ os.path.join(os.path.dirname(__file__), "tmp", filename),
+ ]
+ for path in local_candidates:
+ if os.path.exists(path):
+ return path
+
+ # Download to tmp
+ tmp_dir = os.path.join(os.path.dirname(__file__), "tmp")
+ os.makedirs(tmp_dir, exist_ok=True)
+ tmp_path = os.path.join(tmp_dir, filename)
+ print(f"[Helper] Downloading {filename} from {url} to {tmp_path}")
+ urllib.request.urlretrieve(url, tmp_path)
+ return tmp_path
+
+
opt_name_or_path = get_model_path("facebook/opt-125m")
qwen_name_or_path = get_model_path("Qwen/Qwen3-0.6B")
lamini_name_or_path = get_model_path("MBZUAI/LaMini-GPT-124M")
@@ -332,3 +389,19 @@ def is_model_outputs_similar(model_path_1, model_path_2, metric="cosine_similari
raise ValueError(f"Unknown metric: {metric}. Choose from: 'mse', 'cosine_similarity', 'topk'")
return passed
+
+
+def is_cuda_support_fp8(major=9, minor=0):
+ """Check if the current CUDA device capability is >= (major, minor).
+
+ Args:
+ major: Required major compute capability (default: 9).
+ minor: Required minor compute capability (default: 0).
+
+ Returns:
+ bool: True if CUDA is available and device capability >= (major, minor).
+ """
+ if not torch.cuda.is_available():
+ return False
+ cap = torch.cuda.get_device_capability()
+ return cap >= (major, minor)
diff --git a/test/test_ark/test_model.py b/test/test_ark/test_model.py
index a82a2c7ee..ca0d8b4b6 100644
--- a/test/test_ark/test_model.py
+++ b/test/test_ark/test_model.py
@@ -15,13 +15,17 @@ class TestAutoRoundARKBackend:
@classmethod
def setup_class(self):
self.model_name = get_model_path("facebook/opt-125m")
- self.save_folder = "./saved"
@classmethod
def teardown_class(self):
- shutil.rmtree(self.save_folder, ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_folder = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_folder, ignore_errors=True)
+
def main_op(self, format, bits, group_size, sym, dtype, device, fast_cfg=True, tar_acc=0.27):
limit = 100
if device == "xpu":
@@ -51,7 +55,6 @@ class TestAutoRoundARKBackend:
model_infer(model, tokenizer)
evaluate_accuracy(model, tokenizer, threshold=tar_acc, batch_size=32, limit=limit)
torch.xpu.empty_cache()
- shutil.rmtree(self.save_folder, ignore_errors=True)
@pytest.mark.parametrize("format", ["auto_round", "auto_round:gptqmodel"])
@pytest.mark.parametrize("bits, group_size, sym", [(4, 128, True), (8, 128, True)])
diff --git a/test/test_cpu/backends/test_torch_backend.py b/test/test_cpu/backends/test_torch_backend.py
index 60f7c0662..14951f2e6 100644
--- a/test/test_cpu/backends/test_torch_backend.py
+++ b/test/test_cpu/backends/test_torch_backend.py
@@ -15,11 +15,15 @@ class TestAutoRoundTorchBackend:
@classmethod
def setup_class(self):
self.model_name = get_model_path("facebook/opt-125m")
- self.save_folder = "./saved"
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_folder = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_folder, ignore_errors=True)
@classmethod
def teardown_class(self):
- shutil.rmtree(self.save_folder, ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
def test_torch_4bits_asym(self, dataloader):
@@ -57,7 +61,6 @@ class TestAutoRoundTorchBackend:
model_infer(model, tokenizer)
evaluate_accuracy(model, tokenizer, threshold=0.35, batch_size=16, limit=10)
torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
def test_torch_4bits_sym(self, dataloader):
model = AutoModelForCausalLM.from_pretrained(self.model_name, dtype="auto", trust_remote_code=True)
@@ -85,4 +88,3 @@ class TestAutoRoundTorchBackend:
model_infer(model, tokenizer)
evaluate_accuracy(model, tokenizer, threshold=0.28, batch_size=32, limit=1000)
torch.cuda.empty_cache()
- shutil.rmtree(self.save_folder, ignore_errors=True)
diff --git a/test/test_cpu/core/test_autoopt.py b/test/test_cpu/core/test_autoopt.py
index c14e04c0e..e65ff6436 100644
--- a/test/test_cpu/core/test_autoopt.py
+++ b/test/test_cpu/core/test_autoopt.py
@@ -21,7 +21,6 @@ class TestAutoRound:
# ===== TEARDOWN (teardown_class) =====
print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
def test_Adam(self, tiny_opt_model, opt_tokenizer, dataloader):
diff --git a/test/test_cpu/core/test_autoround.py b/test/test_cpu/core/test_autoround.py
index 701e02ea1..dacd7bf4a 100644
--- a/test/test_cpu/core/test_autoround.py
+++ b/test/test_cpu/core/test_autoround.py
@@ -25,11 +25,15 @@ class TestAutoRound:
model_name = opt_name_or_path
self.model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
- self.save_folder = "./saved"
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_folder = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_folder, ignore_errors=True)
@classmethod
def teardown_class(self):
- shutil.rmtree(self.save_folder, ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
def test_bits_setting(self, tiny_opt_model_path):
@@ -54,7 +58,6 @@ class TestAutoRound:
amp=False,
)
autoround.quantize_and_save(self.save_folder, inplace=False, format="fake")
- shutil.rmtree(self.save_folder, ignore_errors=True)
def test_remove_whole_block(self, tiny_opt_model_path, dataloader):
model_name = tiny_opt_model_path
@@ -79,10 +82,6 @@ class TestAutoRound:
)
autoround.quantize()
- @pytest.mark.skipif(
- transformers_version >= version.parse("5.0"),
- reason="PhiConfig missing pad_token_id, https://github.com/huggingface/transformers/pull/43453",
- )
def test_consecutive_quant(self, tiny_opt_model_path, tiny_phi2_model_path, dataloader):
bits, group_size, sym = 4, -1, False
autoround = AutoRound(
@@ -382,7 +381,6 @@ class TestAutoRound:
tokenizer = AutoTokenizer.from_pretrained(self.save_folder)
model_infer(model, tokenizer)
- shutil.rmtree(self.save_folder, ignore_errors=True)
def test_embed_quant(self, tiny_opt_model_path, dataloader):
bits, group_size, sym = 4, 128, True
@@ -435,7 +433,6 @@ class TestAutoRound:
text = "There is a girl who likes adventure,"
inputs = tokenizer(text, return_tensors="pt").to(model.device)
res = tokenizer.decode(model.generate(**inputs, max_new_tokens=1)[0])
- shutil.rmtree(self.save_folder, ignore_errors=True)
def test_fallback_layers_regex_awq(self, tiny_opt_model_path, dataloader):
model_name = tiny_opt_model_path
@@ -471,7 +468,6 @@ class TestAutoRound:
inputs = tokenizer(text, return_tensors="pt").to(model.device)
res = tokenizer.decode(model.generate(**inputs, max_new_tokens=5)[0])
print(res)
- shutil.rmtree(self.save_folder, ignore_errors=True)
def test_fallback_layers_regex_gptq(self, tiny_opt_model_path, dataloader):
model_name = tiny_opt_model_path
@@ -507,7 +503,6 @@ class TestAutoRound:
inputs = tokenizer(text, return_tensors="pt").to(model.device)
res = tokenizer.decode(model.generate(**inputs, max_new_tokens=5)[0])
print(res)
- shutil.rmtree(self.save_folder, ignore_errors=True)
def test_fallback_layers_regex_round(self, tiny_opt_model_path, dataloader):
model_name = tiny_opt_model_path
@@ -543,7 +538,6 @@ class TestAutoRound:
inputs = tokenizer(text, return_tensors="pt").to(model.device)
res = tokenizer.decode(model.generate(**inputs, max_new_tokens=5)[0])
print(res)
- shutil.rmtree(self.save_folder, ignore_errors=True)
def test_dequant_fp8_weight(self):
from auto_round.utils.model import _dequant_fp8_linear_weight
@@ -680,7 +674,6 @@ class TestAutoRound:
from transformers import AutoTokenizer
model_name = qwen_name_or_path
- # model_name = "/models/Qwen3-0.6B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
text = ["haha", "hello world"]
res = tokenizer(text, return_tensors="pt", max_length=8, padding="max_length", truncation=True)
@@ -698,7 +691,6 @@ class TestAutoRound:
from transformers import AutoTokenizer
model_name = qwen_name_or_path
- # model_name = "/models/Qwen3-0.6B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
text = ["haha", "hello world"]
res = tokenizer(text, return_tensors="pt", max_length=8, padding="max_length", truncation=True)
@@ -732,7 +724,6 @@ class TestAutoRound:
device_map="cpu",
)
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_create_adam(self):
model_name = qwen_name_or_path
diff --git a/test/test_cpu/core/test_autoround_acc.py b/test/test_cpu/core/test_autoround_acc.py
index 4190e3782..ef23186a9 100644
--- a/test/test_cpu/core/test_autoround_acc.py
+++ b/test/test_cpu/core/test_autoround_acc.py
@@ -13,13 +13,14 @@ from ...helpers import gptj_name_or_path
class TestAutoRound:
- @classmethod
- def setup_class(self):
- self.save_dir = "./saved"
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
@classmethod
def teardown_class(self):
- shutil.rmtree(self.save_dir, ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
def test_default_acc(self, dataloader):
@@ -68,4 +69,3 @@ class TestAutoRound:
autoround = AutoRound(model_name, bits=bits, sym=sym, iters=0)
autoround.quantize_and_save(self.save_dir, format="auto_round", inplace=False)
model_args = f"pretrained={self.save_dir}"
- shutil.rmtree(self.save_dir, ignore_errors=True)
diff --git a/test/test_cpu/export/test_export.py b/test/test_cpu/export/test_export.py
index a2212fbc6..2ef2827b2 100644
--- a/test/test_cpu/export/test_export.py
+++ b/test/test_cpu/export/test_export.py
@@ -27,15 +27,19 @@ class TestAutoRound:
@classmethod
def setup_class(self):
self.model_name = opt_name_or_path
- self.save_dir = "./saved"
self.model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
@classmethod
def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
def test_autogptq_format(self, dataloader):
for group_size in [-1, 32, 128]:
bits, sym = 4, False
@@ -50,11 +54,10 @@ class TestAutoRound:
dataset=dataloader,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_gptq")
if group_size == -1:
- shutil.rmtree("./saved", ignore_errors=True)
continue
quantization_config = AutoRoundConfig()
model = AutoModelForCausalLM.from_pretrained(
@@ -64,7 +67,6 @@ class TestAutoRound:
text = "There is a girl who likes adventure,"
inputs = tokenizer(text, return_tensors="pt").to(model.device)
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree("./saved", ignore_errors=True)
def test_autoround_format(self, dataloader):
for group_size in [-1, 32, 128]:
@@ -79,18 +81,16 @@ class TestAutoRound:
seqlen=2,
dataset=dataloader,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
if group_size == -1:
- shutil.rmtree("./saved", ignore_errors=True)
continue
model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="cpu")
tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
text = "There is a girl who likes adventure,"
inputs = tokenizer(text, return_tensors="pt").to(model.device)
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree("./saved", ignore_errors=True)
def test_autoround_awq_format(self, dataloader):
for group_size in [-1, 32, 128]:
@@ -105,7 +105,7 @@ class TestAutoRound:
seqlen=2,
dataset=dataloader,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round:auto_awq")
@@ -120,7 +120,6 @@ class TestAutoRound:
text = "There is a girl who likes adventure,"
inputs = tokenizer(text, return_tensors="pt").to(model.device)
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree("./saved", ignore_errors=True)
def test_autoawq_format(self, dataloader):
for group_size in [-1, 32, 128]:
@@ -136,11 +135,10 @@ class TestAutoRound:
dataset=dataloader,
)
autoround.quantize()
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_awq")
if group_size == -1:
- shutil.rmtree("./saved", ignore_errors=True)
continue
quantization_config = AutoRoundConfig()
@@ -151,7 +149,6 @@ class TestAutoRound:
text = "There is a girl who likes adventure,"
inputs = tokenizer(text, return_tensors="pt").to(model.device)
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree("./saved", ignore_errors=True)
def test_autoround_3bit_asym_format(self, dataloader):
bits, group_size, sym = 3, 128, False
@@ -175,7 +172,6 @@ class TestAutoRound:
text = "There is a girl who likes adventure,"
inputs = tokenizer(text, return_tensors="pt").to(model.device)
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_autoround_3bit_sym_format(self, dataloader):
bits, group_size, sym = 3, 128, True
@@ -199,7 +195,6 @@ class TestAutoRound:
text = "There is a girl who likes adventure,"
inputs = tokenizer(text, return_tensors="pt").to(model.device)
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree(quantized_model_path, ignore_errors=True)
@pytest.mark.parametrize("static_kv_dtype", ["fp8", "float16"])
def test_static_afp8_export(self, static_kv_dtype):
@@ -220,7 +215,7 @@ class TestAutoRound:
seqlen=2,
static_kv_dtype=static_kv_dtype,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
f = safe_open(os.path.join(quantized_model_path, "model.safetensors"), framework="pt")
assert "model.decoder.layers.8.self_attn.k_proj.input_scale" in f.keys()
@@ -264,7 +259,6 @@ class TestAutoRound:
f.get_tensor("model.decoder.layers.5.self_attn.k_scale").dtype == torch.float32
or f.get_tensor("model.decoder.layers.5.self_attn.k_scale").dtype == torch.bfloat16
)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
autoround = AutoRound(
@@ -281,7 +275,7 @@ class TestAutoRound:
act_dynamic=False,
act_group_size=0,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
f = safe_open(os.path.join(quantized_model_path, "model.safetensors"), framework="pt")
@@ -289,7 +283,6 @@ class TestAutoRound:
assert "model.decoder.layers.8.self_attn.k_proj.weight_scale" in f.keys()
assert f.get_tensor("model.decoder.layers.5.self_attn.v_proj.input_scale").shape == torch.Size([1])
assert f.get_tensor("model.decoder.layers.5.self_attn.v_proj.weight").dtype == torch.float8_e4m3fn
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_static_fp8_attn(self):
import os
@@ -307,7 +300,7 @@ class TestAutoRound:
scheme="FP8_STATIC",
static_attention_dtype="fp8",
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
f = safe_open(os.path.join(quantized_model_path, "model.safetensors"), framework="pt")
assert "model.decoder.layers.8.self_attn.k_proj.input_scale" in f.keys()
@@ -321,8 +314,6 @@ class TestAutoRound:
assert f.get_tensor(weight_name).shape == torch.Size([1])
assert f.get_tensor(weight_name).dtype == torch.float32 or f.get_tensor(weight_name).dtype == torch.bfloat16
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
def test_awq_lmhead_export(self, dataloader):
bits, sym, group_size = 4, False, 128
model_name = get_model_path("microsoft/phi-4")
@@ -341,13 +332,12 @@ class TestAutoRound:
layer_config=layer_config,
dataset=dataloader,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_awq")
lm_head = compressed_model.lm_head
from auto_round.export.export_to_awq.utils import WQLinear_GEMM
assert isinstance(lm_head, WQLinear_GEMM), "Illegal AWQ quantization for lm_head layer"
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_gptq_lmhead_export(self, dataloader):
bits, sym, group_size = 4, True, 128
@@ -368,7 +358,7 @@ class TestAutoRound:
layer_config=layer_config,
dataset=dataloader,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_gptq")
lm_head = compressed_model.lm_head
assert hasattr(lm_head, "bits") and lm_head.bits == 4, "Illegal GPTQ quantization for lm_head layer"
@@ -381,7 +371,6 @@ class TestAutoRound:
inputs = tokenizer(text, return_tensors="pt").to(model.device)
res = tokenizer.decode(model.generate(**inputs, max_new_tokens=5)[0])
print(res)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_export_format(self):
from auto_round.formats import get_formats
@@ -464,7 +453,7 @@ class TestAutoRound:
batch_size=1,
dataset=dataloader,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, inplace=False, format="auto_awq")
# Check items of modules_to_not_convert in quantization config
@@ -492,20 +481,18 @@ class TestAutoRound:
seqlen=2,
scheme="INT8_W8A8",
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="llm_compressor")
with safe_open(os.path.join(quantized_model_path, "model.safetensors"), framework="pt") as f:
assert "model.decoder.layers.8.self_attn.k_proj.weight_scale" in f.keys()
assert f.get_tensor("model.decoder.layers.5.self_attn.v_proj.weight").dtype == torch.int8
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_llmc_dynamic_wint8aint8_export_with_tuning(self, dataloader):
from safetensors import safe_open
autoround = AutoRound(self.model_name, iters=1, nsamples=2, seqlen=2, dataset=dataloader, scheme="INT8_W8A8")
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="llm_compressor")
with safe_open(os.path.join(quantized_model_path, "model.safetensors"), framework="pt") as f:
assert "model.decoder.layers.8.self_attn.k_proj.weight_scale" in f.keys()
assert f.get_tensor("model.decoder.layers.5.self_attn.v_proj.weight").dtype == torch.int8
- shutil.rmtree(quantized_model_path, ignore_errors=True)
diff --git a/test/test_cpu/export/test_gguf_format.py b/test/test_cpu/export/test_gguf_format.py
index aae5384eb..e1c38756f 100644
--- a/test/test_cpu/export/test_gguf_format.py
+++ b/test/test_cpu/export/test_gguf_format.py
@@ -9,7 +9,7 @@ from transformers import AutoModelForCausalLM, AutoTokenizer
from auto_round import AutoRound
-from ...helpers import get_model_path, get_tiny_model, save_tiny_model, transformers_version
+from ...helpers import eval_generated_prompt, get_model_path, get_tiny_model, save_tiny_model
AUTO_ROUND_PATH = __file__.split("/")
AUTO_ROUND_PATH = "/".join(AUTO_ROUND_PATH[: AUTO_ROUND_PATH.index("test")])
@@ -24,31 +24,18 @@ class TestGGUF:
@classmethod
def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
- def test_basic_usage(self, tiny_gemma_model_path, tiny_qwen_model_path):
- python_path = sys.executable
- res = os.system(
- f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round --model {tiny_gemma_model_path} "
- f" --bs 16 --iters 0 --nsamples 1 --format gguf:q4_k_m"
- )
- if res > 0 or res == -1:
- assert False, "cmd line test fail, please have a check"
- shutil.rmtree("./saved", ignore_errors=True)
-
- res = os.system(
- f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round --model {tiny_qwen_model_path}"
- f" --bs 16 --iters 1 --nsamples 1 --format fake,gguf:q4_0"
- )
- if res > 0 or res == -1:
- assert False, "cmd line test fail, please have a check"
- shutil.rmtree("./saved", ignore_errors=True)
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
- def test_q4_0(self):
+ def test_q4_0(self, tiny_qwen_model_path):
bits, group_size, sym = 4, 32, True
autoround = AutoRound(
- self.model_name,
+ tiny_qwen_model_path,
bits=bits,
group_size=group_size,
sym=sym,
@@ -57,72 +44,30 @@ class TestGGUF:
nsamples=1,
seqlen=8,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, inplace=False, format="gguf:q4_0")
gguf_file = os.listdir(quantized_model_path)[0]
-
- # TODO: fix the issue of gguf loading error in transformers v5
- # cls = transformers.generation.configuration_utils.GenerationConfig'>, json_file = None
- # def _dict_from_json_file(cls, json_file: str | os.PathLike):
- # > with open(json_file, "r", encoding="utf-8") as reader:
- # E TypeError: expected str, bytes or os.PathLike object, not NoneType
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, gguf_file=gguf_file, device_map="auto")
- text = "There is a girl who likes adventure,"
- inputs = self.tokenizer(text, return_tensors="pt").to(model.device)
- print(self.tokenizer.decode(model.generate(**inputs, max_new_tokens=10)[0]))
-
- shutil.rmtree("./saved", ignore_errors=True)
+ assert gguf_file.endswith(".gguf"), "Saved file is not in gguf format"
+ # Accuracy test is covered in test_cuda/export/test_gguf_format.py::TestAutoRound::test_q4_0_accuracy
def test_func(self):
bits, group_size, sym = 4, 128, True
autoround = AutoRound(
self.model_name,
- iters=1,
- nsamples=1,
- seqlen=10,
- # data_type="int"
+ iters=0,
+ disable_opt_rtn=True,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, inplace=False, format="gguf:q*_1")
assert autoround.group_size == 32
assert not autoround.sym
- gguf_file = os.listdir("saved")[0]
+ gguf_file = os.listdir(self.save_dir)[0]
model = AutoModelForCausalLM.from_pretrained(quantized_model_path, gguf_file=gguf_file, device_map="auto")
- text = "There is a girl who likes adventure,"
- inputs = self.tokenizer(text, return_tensors="pt").to(model.device)
- print(self.tokenizer.decode(model.generate(**inputs, max_new_tokens=10)[0]))
- shutil.rmtree("./saved", ignore_errors=True)
+ eval_generated_prompt(model, self.tokenizer)
- def test_gguf_baseline(self):
- model_name = get_model_path("Qwen/Qwen2.5-1.5B-Instruct")
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
- autoround = AutoRound(
- model,
- self.tokenizer,
- bits=3,
- group_size=16,
- sym=True,
- iters=0,
- nsamples=8,
- seqlen=2,
- data_type="rtn_int_sym_dq",
- super_group_size=16,
- super_bits=6,
- disable_opt_rtn=True,
- )
- quantized_model_path = "./saved"
- autoround.quantize_and_save(output_dir=quantized_model_path, inplace=False, format="fake")
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
- text = "There is a girl who likes adventure,"
- inputs = self.tokenizer(text, return_tensors="pt").to(model.device)
- print(self.tokenizer.decode(model.generate(**inputs, max_new_tokens=10)[0]))
- shutil.rmtree("./saved", ignore_errors=True)
-
- def test_q4_k_m(self, dataloader):
- model_name = get_model_path("Qwen/Qwen2.5-1.5B-Instruct")
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
+ def test_q4_k_m(self, dataloader, tiny_qwen_model_path):
+ model_name = tiny_qwen_model_path
layer_config = {
"lm_head": {
"bits": 4,
@@ -133,12 +78,11 @@ class TestGGUF:
"super_group_size": 8,
},
"model.embed_tokens": {"bits": 6, "group_size": 32, "super_bits": 6, "super_group_size": 8},
- "model.layers.12.mlp.gate_proj": {"bits": 3},
- "model.layers.10.mlp.gate_proj": {"bits": 8},
+ "model.layers.1.mlp.gate_proj": {"bits": 3},
+ "model.layers.0.mlp.gate_proj": {"bits": 8},
}
autoround = AutoRound(
- model,
- tokenizer,
+ model_name,
layer_config=layer_config,
iters=0,
seqlen=1,
@@ -146,25 +90,18 @@ class TestGGUF:
dataset=dataloader,
disable_opt_rtn=True,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="gguf:q4_k_m,fake")
- assert autoround.layer_config["model.layers.11.self_attn.v_proj"]["super_group_size"] == 16
- assert autoround.layer_config["model.layers.11.self_attn.v_proj"]["data_type"] == "int_sym_dq"
- assert autoround.layer_config["model.layers.7.self_attn.v_proj"]["data_type"] == "int_asym_dq"
- assert autoround.model.model.layers[0].self_attn.v_proj.bits == 6
- assert autoround.model.model.layers[12].self_attn.v_proj.bits == 4
+ assert autoround.layer_config["model.layers.1.self_attn.v_proj"]["super_group_size"] == 16
+ assert autoround.layer_config["model.layers.1.self_attn.v_proj"]["data_type"] == "int_sym_dq"
+ assert autoround.layer_config["model.layers.0.self_attn.v_proj"]["data_type"] == "int_asym_dq"
+ assert autoround.model.model.layers[0].self_attn.v_proj.bits == 4
+ assert autoround.model.model.layers[1].self_attn.v_proj.bits == 6
assert autoround.model.model.embed_tokens.bits == 6
assert autoround.model.model.embed_tokens.group_size == 16
- assert autoround.model.model.layers[12].mlp.gate_proj.bits == 3
- assert autoround.model.model.layers[10].mlp.gate_proj.bits == 8
- assert autoround.layer_config["model.layers.10.mlp.gate_proj"]["mostly"] == "gguf:q8_0"
- shutil.rmtree("./saved", ignore_errors=True)
-
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
- autoround = AutoRound(model, tokenizer, iters=0, nsamples=1, seqlen=128, disable_opt_rtn=False)
- quantized_model_path = "./saved"
- autoround.quantize_and_save(output_dir=quantized_model_path, format="gguf:q4_k_m,fake")
- shutil.rmtree("./saved", ignore_errors=True)
+ assert autoround.model.model.layers[1].mlp.gate_proj.bits == 3
+ assert autoround.model.model.layers[0].mlp.gate_proj.bits == 8
+ assert autoround.layer_config["model.layers.0.mlp.gate_proj"]["mostly"] == "gguf:q8_0"
def test_all_format(self, tiny_qwen_model_path):
model_name = tiny_qwen_model_path
@@ -190,63 +127,51 @@ class TestGGUF:
# test mixed q2_k_s
res = os.system(
f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round --model {model_name}"
- f" --bs 16 --iters 0 --nsamples 1 --seqlen 16 --scheme GGUF:Q2_K_MIXED"
+ f" --bs 16 --iters 0 --disable_opt_rtn --nsamples 1 --seqlen 16 --scheme GGUF:Q2_K_MIXED"
)
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
shutil.rmtree("../../tmp_autoround", ignore_errors=True)
- def test_vlm_gguf(self):
- from ...helpers import save_tiny_model
-
- model_name = get_model_path("Qwen/Qwen2-VL-2B-Instruct")
- tiny_model_path = save_tiny_model(model_name, "./tmp/tiny_qwen_vl_model_path", num_layers=3, is_mllm=True)
+ def test_vlm_gguf(self, tiny_qwen_vl_model_path):
from auto_round import AutoRoundMLLM
autoround = AutoRoundMLLM(
- tiny_model_path,
+ tiny_qwen_vl_model_path,
iters=0,
nsamples=8,
disable_opt_rtn=True,
quant_nontext_module=True,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="gguf:q4_0")
- assert "mmproj-model.gguf" in os.listdir("./saved")
+ assert "mmproj-model.gguf" in os.listdir(self.save_dir)
for file_name in os.listdir(quantized_model_path):
file_size = os.path.getsize(os.path.join(quantized_model_path, file_name)) / 1024**2
if file_name == "mmproj-model.gguf":
- assert abs(file_size - 56) < 5.0
+ assert file_size < 60, f"file size {file_size} MB is too large for non-quantized mmproj-model.gguf"
else:
- assert abs(file_size - 264) < 5.0
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree(tiny_model_path, ignore_errors=True)
-
- def test_vlm_gguf_wo_quant_nontext_module(self):
- from ...helpers import save_tiny_model
+ assert file_size < 270, f"file size {file_size} MB is too large for non-quantized mmproj-model.gguf"
- model_name = get_model_path("Qwen/Qwen2-VL-2B-Instruct")
- tiny_model_path = save_tiny_model(model_name, "./tmp/tiny_qwen_vl_model_path", num_layers=3, is_mllm=True)
+ def test_vlm_gguf_wo_quant_nontext_module(self, tiny_qwen_vl_model_path):
from auto_round import AutoRoundMLLM
autoround = AutoRoundMLLM(
- tiny_model_path,
+ tiny_qwen_vl_model_path,
iters=0,
nsamples=8,
disable_opt_rtn=True,
quant_nontext_module=False,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="gguf:q4_0")
- assert "mmproj-model.gguf" in os.listdir("./saved")
+ assert "mmproj-model.gguf" in os.listdir(self.save_dir)
for file_name in os.listdir(quantized_model_path):
file_size = os.path.getsize(os.path.join(quantized_model_path, file_name)) / 1024**2
if file_name == "mmproj-model.gguf":
assert abs(file_size - 361) < 5.0
else:
assert abs(file_size - 264) < 5.0
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree(tiny_model_path, ignore_errors=True)
def test_qtype_setting(self):
# Qwen2.5-0.5B-Instruct no output, token_embed q6_k fallbakc to q8_0 336M
@@ -319,26 +244,20 @@ class TestGGUF:
and ar.layer_config["model.embed_tokens"]["super_bits"] == 8
)
- def test_q2k_mixed(self):
- model_name = get_model_path("Qwen/Qwen1.5-MoE-A2.7B")
- saved_tiny_model_path = save_tiny_model(
- model_name,
- "./tmp/tiny_qwen_model_path",
- num_layers=3,
- is_mllm=False,
- )
+ def test_q2k_mixed(self, tiny_qwen_moe_model_path):
+ model_name = tiny_qwen_moe_model_path
autoround = AutoRound(
- saved_tiny_model_path,
+ model_name,
iters=0,
nsamples=1,
seqlen=16,
disable_opt_rtn=True,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="gguf:q2_k_mixed")
gguf_file = os.listdir(quantized_model_path)[0]
file_size = os.path.getsize(os.path.join(quantized_model_path, gguf_file)) / 1024**2
- assert abs(file_size - 1362) < 5.0
+ assert file_size < 1150, f"file size {file_size} MB is too large for q2_k_mixed format"
from gguf.gguf_reader import GGUFReader
gguf_model = GGUFReader(os.path.join(quantized_model_path, gguf_file))
@@ -346,6 +265,3 @@ class TestGGUF:
assert gguf_model.get_tensor(2).tensor_type.name == "Q4_K"
assert gguf_model.get_tensor(10).name == "blk.0.ffn_up_exps.weight"
assert gguf_model.get_tensor(10).tensor_type.name == "Q2_K"
-
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree(saved_tiny_model_path, ignore_errors=True)
diff --git a/test/test_cpu/integrations/test_llmcompressor.py b/test/test_cpu/export/test_llmc_format.py
similarity index 84%
rename from test/test_cpu/integrations/test_llmcompressor.py
rename to test/test_cpu/export/test_llmc_format.py
index c2966cedd..ebc1bd87c 100644
--- a/test/test_cpu/integrations/test_llmcompressor.py
+++ b/test/test_cpu/export/test_llmc_format.py
@@ -19,9 +19,14 @@ class TestLLMC:
@classmethod
def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
# remove since w8a8 not in llmcompressor format supported schemes
# def test_llmcompressor_w8a8(self):
# bits, group_size, sym, act_bits = 8, -1, True, 8
@@ -50,15 +55,15 @@ class TestLLMC:
nsamples=2,
iters=0,
)
- autoround.quantize_and_save("./saved", format="llm_compressor")
+ autoround.quantize_and_save(self.save_dir, format="llm_compressor")
# from vllm import LLM
- # model = LLM("./saved")
+ # model = LLM(self.save_dir)
# result = model.generate("Hello my name is")
# print(result)
import json
- config = json.load(open("./saved/config.json"))
+ config = json.load(open(os.path.join(self.save_dir, "config.json")))
assert "group_0" in config["quantization_config"]["config_groups"]
assert config["quantization_config"]["config_groups"]["group_0"]["input_activations"]["num_bits"] == 8
assert config["quantization_config"]["config_groups"]["group_0"]["weights"]["strategy"] == "channel"
@@ -75,11 +80,11 @@ class TestLLMC:
nsamples=2,
iters=0,
)
- autoround.quantize_and_save("./saved", format="auto_round:llm_compressor")
+ autoround.quantize_and_save(self.save_dir, format="auto_round:llm_compressor")
import json
- config = json.load(open("./saved/config.json"))
+ config = json.load(open(os.path.join(self.save_dir, "config.json")))
assert "group_0" in config["quantization_config"]["config_groups"]
assert config["quantization_config"]["config_groups"]["group_0"]["input_activations"]["num_bits"] == 8
assert config["quantization_config"]["config_groups"]["group_0"]["weights"]["strategy"] == "tensor"
diff --git a/test/test_cpu/integrations/test_llmc_integration.py b/test/test_cpu/integrations/test_llmc_integration.py
index 069d4fe06..23bd55d07 100644
--- a/test/test_cpu/integrations/test_llmc_integration.py
+++ b/test/test_cpu/integrations/test_llmc_integration.py
@@ -3,19 +3,18 @@ import torch
from compressed_tensors.quantization import QuantizationArgs, QuantizationScheme
from llmcompressor import oneshot
from llmcompressor.modifiers.autoround import AutoRoundModifier
-from packaging import version
from transformers import AutoModelForCausalLM, AutoTokenizer
from auto_round.calib_dataset import get_dataset
-from ...helpers import transformers_version
+from ...envs import multi_card
recipe_str = """
quant_stage:
quant_modifiers:
AutoRoundModifier:
ignore: ["lm_head"]
- iters: 1
+ iters: 10
config_groups:
group_0:
targets:
@@ -32,7 +31,7 @@ quant_stage:
recipe_modifier_full = AutoRoundModifier(
ignore=["lm_head"],
- iters=1,
+ iters=10,
config_groups={
"group_0": QuantizationScheme(
targets=["Linear"],
@@ -40,31 +39,122 @@ recipe_modifier_full = AutoRoundModifier(
)
},
)
+recipe_modifier_nvfp4 = AutoRoundModifier(
+ ignore=["lm_head"],
+ iters=2,
+ scheme="NVFP4",
+)
+recipe_modifier_mxfp4 = AutoRoundModifier(
+ ignore=["lm_head"],
+ iters=0,
+ scheme="MXFP4",
+)
- transformers_version >= version.parse("5.0.0"),
- reason="transformers 5.0 use_auth_token is deprecated and llmcompressor oneshot has not been updated yet, \
- https://github.com/vllm-project/llm-compressor/issues/2289",
+w8a8_dynamic_recipe_modifier = AutoRoundModifier(
+ ignore=["lm_head"],
+ iters=0,
+ config_groups={
+ "group_0": QuantizationScheme(
+ targets=["Linear"],
+ weights=QuantizationArgs(num_bits=8, type="float", strategy="channel"),
+ input_activations=QuantizationArgs(num_bits=8, type="float", strategy="token", dynamic=True),
+ )
+ },
+)
+
+w8a8_static_recipe_modifier = AutoRoundModifier(
+ ignore=["lm_head"],
+ iters=0,
+ config_groups={
+ "group_0": QuantizationScheme(
+ targets=["Linear"],
+ weights=QuantizationArgs(num_bits=8, type="float", strategy="tensor"),
+ input_activations=QuantizationArgs(num_bits=8, type="float", strategy="tensor"),
+ )
+ },
)
+
+
@pytest.mark.parametrize(
"recipe",
[
recipe_str,
recipe_modifier_full,
+ recipe_modifier_nvfp4,
+ recipe_modifier_mxfp4,
],
)
-def test_oneshot_application(recipe, tmp_path):
+def test_oneshot_application(tiny_tiny_llama_model_path, recipe, tmp_path):
output = tmp_path / "oneshot_output"
- model = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
+ model = tiny_tiny_llama_model_path
+ tokenizer = AutoTokenizer.from_pretrained(model)
+ dataset = get_dataset(
+ tokenizer=tokenizer,
+ seqlen=1024,
+ nsamples=32,
+ )
+
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
+
+ oneshot(
+ model=model,
+ dataset=dataset,
+ output_dir=output,
+ recipe=recipe,
+ )
+ model_loaded = AutoModelForCausalLM.from_pretrained(output, device_map=device)
+
+ # Check that the model is quantized
+ # decompress() will attach a quantization_config to the model
+ # as we decompress right away
+ quantization_config = model_loaded.config.quantization_config.quantization_config
+ assert quantization_config is not None
+
+ # check config is set properly
+ assert "lm_head" in quantization_config.ignore
+ assert len(quantization_config.config_groups) == 1
+ quant_scheme = quantization_config.config_groups["group_0"]
+ assert isinstance(quant_scheme, QuantizationScheme)
+
+ weight_args = quantization_config.config_groups["group_0"].weights
+ assert isinstance(weight_args, QuantizationArgs)
+ assert weight_args.num_bits == 4
+
+ # Check a specific layer is quantized
+ targeted_linear_layer = model_loaded.model.layers[2].self_attn.q_proj
+ assert hasattr(targeted_linear_layer, "quantization_scheme")
+
+ # Check lm-head is not quantized
+ not_targeted = model_loaded.lm_head
+ assert not hasattr(not_targeted, "quantization_scheme")
+
+
+@multi_card
+def test_oneshot_with_device_ids(tiny_tiny_llama_model_path, tmp_path):
+ output = tmp_path / "oneshot_output"
+ model = tiny_tiny_llama_model_path
tokenizer = AutoTokenizer.from_pretrained(model)
dataset = get_dataset(
tokenizer=tokenizer,
- seqlen=16,
- nsamples=2,
+ seqlen=512,
+ nsamples=4,
)
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
+ recipe = AutoRoundModifier(
+ ignore=["lm_head"],
+ iters=10,
+ config_groups={
+ "group_0": QuantizationScheme(
+ targets=["Linear"],
+ weights=QuantizationArgs(num_bits=4, strategy="group", group_size=128),
+ )
+ },
+ device_ids="0,1",
+ )
+
oneshot(
model=model,
dataset=dataset,
@@ -74,11 +164,8 @@ def test_oneshot_application(recipe, tmp_path):
model_loaded = AutoModelForCausalLM.from_pretrained(output, device_map=device)
# Check that the model is quantized
- # for compression_config - decompress() will attach a quantization_config
- # to the model as we decompress right away
- # for quantization_config - we have CompressedLinear which will only
- # decompress on the forward pass and does not call decompress(). Results
- # in a slightly different parameter tree to access the quant config
+ # decompress() will attach a quantization_config to the model
+ # as we decompress right away
quantization_config = model_loaded.config.quantization_config.quantization_config
assert quantization_config is not None
@@ -93,7 +180,58 @@ def test_oneshot_application(recipe, tmp_path):
assert weight_args.num_bits == 4
# Check a specific layer is quantized
- targeted_linear_layer = model_loaded.model.layers[1].self_attn.q_proj
+ targeted_linear_layer = model_loaded.model.layers[2].self_attn.q_proj
+ assert hasattr(targeted_linear_layer, "quantization_scheme")
+
+ # Check lm-head is not quantized
+ not_targeted = model_loaded.lm_head
+ assert not hasattr(not_targeted, "quantization_scheme")
+
+
+ "recipe",
+ [w8a8_dynamic_recipe_modifier, w8a8_static_recipe_modifier],
+)
+def test_rtn_oneshot(recipe, tmp_path):
+ output = tmp_path / "oneshot_output"
+ model = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
+ tokenizer = AutoTokenizer.from_pretrained(model)
+ dataset = get_dataset(
+ tokenizer=tokenizer,
+ seqlen=1024,
+ nsamples=32,
+ )
+
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
+
+ oneshot(
+ model=model,
+ dataset=dataset,
+ output_dir=output,
+ recipe=recipe,
+ )
+ model_loaded = AutoModelForCausalLM.from_pretrained(output, device_map=device)
+
+ quantization_config = model_loaded.config.quantization_config.quantization_config
+ assert quantization_config is not None
+
+ # check config is set properly
+ assert "lm_head" in quantization_config.ignore
+ assert len(quantization_config.config_groups) == 1
+ quant_scheme = quantization_config.config_groups["group_0"]
+ assert isinstance(quant_scheme, QuantizationScheme)
+
+ weight_args = quantization_config.config_groups["group_0"].weights
+ act_args = quantization_config.config_groups["group_0"].input_activations
+ assert isinstance(weight_args, QuantizationArgs)
+ assert weight_args.num_bits == recipe.config_groups["group_0"].weights.num_bits
+ assert weight_args.strategy == recipe.config_groups["group_0"].weights.strategy
+ if act_args is not None:
+ assert act_args.num_bits == recipe.config_groups["group_0"].input_activations.num_bits
+ assert act_args.strategy == recipe.config_groups["group_0"].input_activations.strategy
+
+ # Check a specific layer is quantized
+ targeted_linear_layer = model_loaded.model.layers[2].self_attn.q_proj
assert hasattr(targeted_linear_layer, "quantization_scheme")
# Check lm-head is not quantized
diff --git a/test/test_cpu/models/test_block_names.py b/test/test_cpu/models/test_block_names.py
index 8394e1cc7..c51f64c93 100644
--- a/test/test_cpu/models/test_block_names.py
+++ b/test/test_cpu/models/test_block_names.py
@@ -113,9 +113,12 @@ class TestQuantizationBlocks:
@classmethod
def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ @pytest.fixture(autouse=True)
+ def setup_save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+
def test_moe_quant(self):
input_size = 10
hidden_size = 10
@@ -166,7 +169,7 @@ class TestQuantizationBlocks:
)
autoround.quantize()
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.save_quantized(quantized_model_path, inplace=False, safe_serialization=False, format="auto_round")
model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
@@ -176,7 +179,6 @@ class TestQuantizationBlocks:
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
quant_config = model.config.quantization_config
assert quant_config.block_name_to_quantize is not None
- shutil.rmtree("./saved", ignore_errors=True)
def test_mm_block_name(self, tiny_qwen_vl_model_path):
from transformers import Qwen2VLForConditionalGeneration
diff --git a/test/test_cpu/models/test_conv1d.py b/test/test_cpu/models/test_conv1d.py
index 9e151c3f0..8a30b8207 100644
--- a/test/test_cpu/models/test_conv1d.py
+++ b/test/test_cpu/models/test_conv1d.py
@@ -18,9 +18,12 @@ class TestQuantizationConv1d:
@classmethod
def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ @pytest.fixture(autouse=True)
+ def setup_save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+
def test_quant(self, dataloader):
self.model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
bits, group_size, sym = 4, 128, True
@@ -36,7 +39,7 @@ class TestQuantizationConv1d:
)
autoround.quantize()
- autoround.save_quantized("./saved")
+ autoround.save_quantized(self.save_dir)
- model = AutoModelForCausalLM.from_pretrained("./saved", device_map="cpu", trust_remote_code=True)
+ model = AutoModelForCausalLM.from_pretrained(self.save_dir, device_map="cpu", trust_remote_code=True)
model_infer(model, self.tokenizer)
diff --git a/test/test_cpu/models/test_diffusion.py b/test/test_cpu/models/test_diffusion.py
index 4439131f4..6b0dc0f76 100644
--- a/test/test_cpu/models/test_diffusion.py
+++ b/test/test_cpu/models/test_diffusion.py
@@ -24,10 +24,6 @@ def setup_flux():
return pipe, output_dir
- transformers_version >= version.parse("5.0.0"),
- reason="cannot import name 'MT5Tokenizer' from 'transformers', https://github.com/huggingface/diffusers/issues/13035",
-)
def test_flux_saving(setup_flux):
pipe, output_dir = setup_flux
autoround = AutoRound(
@@ -44,10 +40,6 @@ def test_flux_saving(setup_flux):
shutil.rmtree(output_dir, ignore_errors=True)
- transformers_version >= version.parse("5.0.0"),
- reason="cannot import name 'MT5Tokenizer' from 'transformers', https://github.com/huggingface/diffusers/issues/13035",
-)
def test_flux(setup_flux):
pipe, output_dir = setup_flux
autoround = AutoRound(
diff --git a/test/test_cpu/models/test_mllm.py b/test/test_cpu/models/test_mllm.py
index 7450cd8ab..9fd6c69df 100644
--- a/test/test_cpu/models/test_mllm.py
+++ b/test/test_cpu/models/test_mllm.py
@@ -35,9 +35,12 @@ class TestAutoRoundMLLM:
@classmethod
def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ @pytest.fixture(autouse=True)
+ def setup_save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+
def test_tune(self, tiny_qwen_vl_model_path):
bits, group_size = 4, 128
autoround = AutoRoundMLLM(
@@ -51,8 +54,8 @@ class TestAutoRoundMLLM:
seqlen=10,
)
autoround.quantize()
- autoround.save_quantized("./saved/", format="auto_gptq", inplace=False)
- autoround.save_quantized("./saved/", format="auto_round", inplace=False)
+ autoround.save_quantized(self.save_dir, format="auto_gptq", inplace=False)
+ autoround.save_quantized(self.save_dir, format="auto_round", inplace=False)
def test_quant_vision(self, tiny_qwen_vl_model_path): ## bug need to fix
tokenizer = AutoTokenizer.from_pretrained(tiny_qwen_vl_model_path)
@@ -75,7 +78,7 @@ class TestAutoRoundMLLM:
seqlen=10,
)
autoround.quantize()
- autoround.save_quantized("./saved/", format="auto_round", inplace=True)
+ autoround.save_quantized(self.save_dir, format="auto_round", inplace=True)
def test_quant_block_names(self):
from auto_round.utils import find_matching_blocks, get_block_names
@@ -164,7 +167,7 @@ class TestAutoRoundMLLM:
seqlen=1,
)
autoround.quantize()
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.save_quantized(quantized_model_path, format="auto_round", inplace=False)
import requests
from PIL import Image
@@ -222,15 +225,15 @@ class TestAutoRoundMLLM:
processor=processor,
image_processor=image_processor,
)
- autoround.quantize_and_save("./saved/", format="auto_round")
+ autoround.quantize_and_save(self.save_dir, format="auto_round")
import requests
from PIL import Image
from transformers import AutoProcessor, AutoTokenizer, Qwen2_5_VLForConditionalGeneration
- model = Qwen2_5_VLForConditionalGeneration.from_pretrained("./saved", torch_dtype="auto", device_map="auto")
+ model = Qwen2_5_VLForConditionalGeneration.from_pretrained(self.save_dir, torch_dtype="auto", device_map="auto")
image_url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
- processor = AutoProcessor.from_pretrained("./saved")
+ processor = AutoProcessor.from_pretrained(self.save_dir)
messages = [
{
"role": "user",
diff --git a/test/test_cuda/models/test_moe_experts_interface.py b/test/test_cpu/models/test_moe_experts_interface.py
similarity index 100%
rename from test/test_cuda/models/test_moe_experts_interface.py
rename to test/test_cpu/models/test_moe_experts_interface.py
diff --git a/test/test_cpu/models/test_moe_model.py b/test/test_cpu/models/test_moe_model.py
index 66d20da91..ff7a9e732 100644
--- a/test/test_cpu/models/test_moe_model.py
+++ b/test/test_cpu/models/test_moe_model.py
@@ -3,77 +3,25 @@ import shutil
import pytest
import torch
import torch.nn as nn
-from packaging import version
+import transformers
from transformers import AutoConfig, AutoProcessor, AutoTokenizer, Llama4ForConditionalGeneration
from transformers.models.gpt_oss.modeling_gpt_oss import GptOssForCausalLM
from transformers.models.qwen3_vl_moe.modeling_qwen3_vl_moe import Qwen3VLMoeForConditionalGeneration
from auto_round import AutoRound
-from ...helpers import get_model_path, transformers_version
-
-gpt_oss_name_or_path = get_model_path("openai/gpt-oss-20b")
-llama4_name_or_path = get_model_path("meta-llama/Llama-4-Scout-17B-16E-Instruct")
-qwen3_vl_moe_name_or_path = get_model_path("Qwen/Qwen3-VL-30B-A3B-Instruct")
-# local path for debug
-# llama4_name_or_path = get_model_path("/dataset/Llama-4-Scout-17B-16E-Instruct")
-
-
-def setup_gpt_oss():
- """Fixture to set up the GPT-OSS model and tokenizer."""
- model_name = gpt_oss_name_or_path
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
- config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
- config.num_hidden_layers = 1 # Reduce layers for testing
- model = GptOssForCausalLM(config)
- output_dir = "./tmp/test_quantized_gpt_oss"
- return model, tokenizer, output_dir, config
-
-
-def setup_llama4():
- """Fixture to set up the llama4 model and tokenizer."""
- model_name = llama4_name_or_path
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
- config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
-
- # TODO: Remove after https://github.com/huggingface/transformers/issues/43525 is resolved
- config.pad_token_id = None
-
- config.vision_config.num_hidden_layers = 1 # Reduce layers for testing
- config.text_config.num_hidden_layers = 1
- # config.vision_config.rope_theta = config.vision_config.rope_parameters["rope_theta"] # for transformers >= 5.0
- model = Llama4ForConditionalGeneration(config)
- output_dir = "./tmp/test_quantized_llama4"
- return model, tokenizer, output_dir, config
-
-
-def setup_qwen3_vl_moe():
- """Fixture to set up the qwen3_vl_moe model and tokenizer."""
- model_name = qwen3_vl_moe_name_or_path
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- config = AutoConfig.from_pretrained(model_name)
- config.vision_config.num_hidden_layers = 1
- config.text_config.num_hidden_layers = 1
- config.num_hidden_layers = 1 # Reduce layers for testing
- processor = AutoProcessor.from_pretrained(model_name)
- model = Qwen3VLMoeForConditionalGeneration(config)
- output_dir = "/tmp/test_quantized_qwen3_vl_moe"
- return model, tokenizer, processor, output_dir, config
-
-def quantize_model(model, tokenizer, output_dir, scheme, iters=0, ignore_layers="self_attn,router,lm_head,mlp.gate"):
+def quantize_model(model, output_dir, scheme, iters=0, ignore_layers="self_attn,router,lm_head,mlp.gate"):
"""Helper function to quantize the model with the given scheme."""
+ disable_opt_rtn = True if iters == 0 else False
autoround = AutoRound(
model,
- tokenizer,
scheme=scheme,
nsamples=2,
iters=iters,
seqlen=32,
ignore_layers=ignore_layers,
+ disable_opt_rtn=disable_opt_rtn,
)
quantized_model, save_folder = autoround.quantize_and_save(format="auto_round", output_dir=output_dir)
return quantized_model
@@ -93,14 +41,10 @@ def count_modules_by_type(model, target_module_name_or_class):
@pytest.mark.parametrize("scheme", ["MXFP4", "MXFP8"])
-def test_gptoss(setup_gpt_oss, scheme):
- model, tokenizer, output_dir, config = setup_gpt_oss
-
- # Below parameter is set to be same as the full model
- # Remove it to avoid mismatch during quantized model loading
- delattr(model.config, "layer_types")
-
- quantized_model = quantize_model(model, tokenizer, output_dir, scheme, ignore_layers="self_attn,lm_head")
+def test_gptoss(scheme, tiny_gpt_oss_model_path, tmp_path):
+ config = AutoConfig.from_pretrained(tiny_gpt_oss_model_path, trust_remote_code=True)
+ output_dir = str(tmp_path / "saved")
+ quantized_model = quantize_model(tiny_gpt_oss_model_path, output_dir, scheme, ignore_layers="self_attn,lm_head")
# Ensure the quantized model is not None
assert quantized_model is not None, "Quantized model should not be None."
@@ -108,7 +52,9 @@ def test_gptoss(setup_gpt_oss, scheme):
from auto_round.modeling.fused_moe.gpt_oss import GPTOssSingleExpert
single_expert_cnt = count_modules_by_type(quantized_model, GPTOssSingleExpert)
+ single_expert_cnt += count_modules_by_type(quantized_model, "_ExpertContainer") # for Transformers >= 5.0.0
quant_linear_cnt = count_modules_by_type(quantized_model, QuantLinear)
+
assert (
single_expert_cnt == config.num_local_experts
), f"Expected {config.num_local_experts} GPTOssSingleExpert modules, found {single_expert_cnt}."
@@ -116,29 +62,23 @@ def test_gptoss(setup_gpt_oss, scheme):
quant_linear_cnt == config.num_hidden_layers * 3 * config.num_local_experts
), f"Expected {config.num_hidden_layers * 3 * config.num_local_experts} QuantLinear modules, found {quant_linear_cnt}."
- print(f"[{scheme}] Total {GPTOssSingleExpert.__name__} modules: {single_expert_cnt}")
- print(f"[{scheme}] Total {QuantLinear.__name__} modules: {quant_linear_cnt}")
-
- if scheme == "MXFP4":
- loaded_model = GptOssForCausalLM.from_pretrained(output_dir)
- for n, m in quantized_model.named_modules():
- if m.__class__.__name__ == "QuantLinear":
- loaded_m = loaded_model.get_submodule(n)
+ # verify the quantized model can be loaded and run inference
+ loaded_model = GptOssForCausalLM.from_pretrained(output_dir)
+ for n, m in quantized_model.named_modules():
+ if m.__class__.__name__ == "QuantLinear":
+ loaded_m = loaded_model.get_submodule(n)
+ if scheme == "MXFP4":
assert (loaded_m.weight_packed.to("cpu") == m.weight_packed.to("cpu")).all()
- # clean the output directory after test
- shutil.rmtree(output_dir, ignore_errors=True)
-
-
-def test_llama4(setup_llama4):
- model, tokenizer, output_dir, config = setup_llama4
+ if scheme == "MXFP8":
+ assert (loaded_m.weight.to("cpu") == m.weight.to("cpu")).all()
+ inp = torch.randint(0, 100, (1, 32))
+ with torch.inference_mode():
+ loaded_out = loaded_model(inp)
- # Below parameters are set to be same as the full model
- # Remove them to avoid mismatch during quantized model loading
- model.config.text_config.no_rope_layers = []
- delattr(model.config.text_config, "moe_layers")
- delattr(model.config.text_config, "layer_types")
- quantized_model = quantize_model(model, tokenizer, output_dir, "MXFP4", ignore_layers="self_attn,router,lm_head")
+def test_llama4(tiny_llama4_model_path):
+ output_dir = "./tmp/test_quantized_llama4"
+ quantized_model = quantize_model(tiny_llama4_model_path, output_dir, "MXFP4", ignore_layers="self_attn,lm_head")
# Ensure the quantized model is not None
assert quantized_model is not None, "Quantized model should not be None."
@@ -148,21 +88,23 @@ def test_llama4(setup_llama4):
if m.__class__.__name__ == "QuantLinear":
loaded_m = loaded_model.get_submodule(n)
assert (loaded_m.weight_packed.to("cpu") == m.weight_packed.to("cpu")).all()
+ inp = torch.randint(0, 100, (1, 32))
+ with torch.inference_mode():
+ loaded_out = loaded_model(inp)
# clean the output directory after test
shutil.rmtree(output_dir, ignore_errors=True)
-def test_qwen3_vl_moe_mxfp(setup_qwen3_vl_moe):
- model, tokenizer, processor, output_dir, config = setup_qwen3_vl_moe
+def test_qwen3_vl_moe_mxfp(tiny_qwen3_vl_moe_model_path):
+ output_dir = "/tmp/test_quantized_qwen3_vl_moe"
autoround = AutoRound(
- model,
- tokenizer=tokenizer,
- processor=processor,
+ tiny_qwen3_vl_moe_model_path,
scheme="MXFP4",
nsamples=2,
seqlen=32,
- iters=1,
- ignore_layers="self_attn,lm_head,mlp.gate",
+ iters=0,
+ disable_opt_rtn=True,
+ ignore_layers="self_attn,lm_head, mlp.gate",
)
quantized_model, _ = autoround.quantize_and_save(format="auto_round", output_dir=output_dir)
assert quantized_model is not None, "Quantized model should not be None."
@@ -172,12 +114,9 @@ def test_qwen3_vl_moe_mxfp(setup_qwen3_vl_moe):
if m.__class__.__name__ == "QuantLinear":
loaded_m = loaded_model.get_submodule(n)
assert (loaded_m.weight_packed.to("cpu") == m.weight_packed.to("cpu")).all()
- # test generation
- tokenizer = AutoTokenizer.from_pretrained(output_dir)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(device=loaded_model.device)
- print(tokenizer.decode(loaded_model.generate(**inputs, max_new_tokens=50)[0]))
- # clean the output directory after test
+ inp = torch.randint(0, 100, (1, 32))
+ with torch.inference_mode():
+ loaded_out = loaded_model(inp)
shutil.rmtree(output_dir, ignore_errors=True)
diff --git a/test/test_cpu/models/test_omni_model.py b/test/test_cpu/models/test_omni_model.py
index 8cd83b8bf..ebd1997cf 100644
--- a/test/test_cpu/models/test_omni_model.py
+++ b/test/test_cpu/models/test_omni_model.py
@@ -282,10 +282,14 @@ class TestQwen3OmniMoeReplacement:
"""Test that replaced MoE forward output matches original."""
from auto_round.modeling.fused_moe.replace_modules import apply_replacements, materialize_model_
+ # Fix seed for deterministic model weights and use small-scale input to
+ # prevent numerical overflow with random weights (talker has a larger
+ # shared_expert MLP that can produce NaN otherwise).
+ torch.manual_seed(0)
config = _make_tiny_qwen3_omni_moe_config()
model = Qwen3OmniMoeForConditionalGeneration(config)
- x = torch.randn(1, 4, 64)
+ x = torch.randn(1, 4, 64) * 0.1
with torch.no_grad():
orig_thinker_out = model.thinker.model.layers[0].mlp(x)
orig_talker_out = model.talker.model.layers[0].mlp(x)
@@ -365,9 +369,10 @@ class TestQwen3OmniMoeUtils:
model = Qwen3OmniMoeForConditionalGeneration(config)
ignore_layers = get_predefined_ignore_layers(model)
- assert (
- "mlp.gate" in ignore_layers
- ), f"Expected mlp.gate in ignore_layers for qwen3_omni_moe, got: {ignore_layers}"
+ assert ignore_layers == [
+ "thinker.model.layers.0.mlp.gate",
+ "talker.model.layers.0.mlp.gate",
+ ], f"Expected mlp.gate in ignore_layers for qwen3_omni_moe, got: {ignore_layers}"
class TestQwen2_5OmniNotMoe:
diff --git a/test/test_cpu/quantization/test_act_quantization.py b/test/test_cpu/quantization/test_act_quantization.py
index 014d80f6f..4798e0fe4 100644
--- a/test/test_cpu/quantization/test_act_quantization.py
+++ b/test/test_cpu/quantization/test_act_quantization.py
@@ -9,19 +9,14 @@ from auto_round import AutoRound
class TestAutoRoundAct:
- save_dir = "./saved"
-
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
+ @pytest.fixture(autouse=True)
+ def setup_save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
+ @classmethod
+ def teardown_class(cls):
shutil.rmtree("runs", ignore_errors=True)
def test_mx_fp4(self, tiny_opt_model, opt_tokenizer, dataloader):
@@ -121,7 +116,6 @@ class TestAutoRoundAct:
kproj_config = model.config.quantization_config.extra_config["model.decoder.layers.1.self_attn.k_proj"]
assert "act_bits" in kproj_config.keys() and kproj_config["act_bits"] == 8
assert "bits" in kproj_config.keys() and kproj_config["bits"] == 8
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_act_config_NVFP4_saving(self, tiny_opt_model_path, dataloader):
scheme = "NVFP4"
@@ -140,7 +134,6 @@ class TestAutoRoundAct:
kproj_config = model.config.quantization_config.extra_config["model.decoder.layers.1.self_attn.k_proj"]
assert "act_bits" in kproj_config.keys() and kproj_config["act_bits"] == 16
assert "bits" in kproj_config.keys() and kproj_config["bits"] == 16
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_WOQ_config_INT_saving(self, tiny_opt_model_path, dataloader):
scheme = "W4A16"
@@ -162,7 +155,6 @@ class TestAutoRoundAct:
# check inblock layer config values
kproj_config = extra_config["model.decoder.layers.1.self_attn.k_proj"]
assert "bits" in kproj_config.keys() and kproj_config["bits"] == 8
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_act_config_FP8_saving(self, tiny_opt_model_path, dataloader):
scheme = "FP8_STATIC"
@@ -196,4 +188,3 @@ class TestAutoRoundAct:
kproj_config = extra_config["model.decoder.layers.0.self_attn.k_proj"]
assert "act_bits" in kproj_config.keys() and kproj_config["act_bits"] == 16
assert "group_size" in kproj_config.keys() and kproj_config["group_size"] == 0
- shutil.rmtree(quantized_model_path, ignore_errors=True)
diff --git a/test/test_cpu/quantization/test_asym.py b/test/test_cpu/quantization/test_asym.py
index 60730686f..05f9c1990 100644
--- a/test/test_cpu/quantization/test_asym.py
+++ b/test/test_cpu/quantization/test_asym.py
@@ -1,99 +1,82 @@
import copy
import shutil
import sys
-import unittest
-
-sys.path.insert(0, "../..")
+import pytest
import torch
from transformers import AutoModelForCausalLM, AutoRoundConfig, AutoTokenizer
from auto_round import AutoRound
-from ...helpers import get_model_path
-
-
-class LLMDataLoader:
- def __init__(self):
- self.batch_size = 1
+from ...helpers import get_model_path, model_infer
- def __iter__(self):
- for i in range(3):
- yield torch.ones([1, 10], dtype=torch.long)
-
-class TestAutoRoundAsym(unittest.TestCase):
- @classmethod
- def setUpClass(self):
- # self.model_name = "/models/opt-125m"
- self.model_name = get_model_path("facebook/opt-125m")
- self.save_folder = "./saved"
+class TestAutoRoundAsym:
+ @pytest.fixture(autouse=True)
+ def setup_save_folder(self, tmp_path):
+ self.save_folder = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_folder, ignore_errors=True)
@classmethod
- def tearDownClass(self):
- shutil.rmtree(self.save_folder, ignore_errors=True)
+ def teardown_class(cls):
shutil.rmtree("runs", ignore_errors=True)
- def test_asym_group_size(self):
- model_name = self.model_name
+ def test_asym_group_size(self, tiny_opt_model_path):
for group_size in [32, 64, 128]:
- model = AutoModelForCausalLM.from_pretrained(model_name, dtype="auto")
- tokenizer = AutoTokenizer.from_pretrained(model_name)
bits, sym = 4, False
- ar = AutoRound(model, tokenizer, bits=bits, group_size=group_size, sym=sym, iters=0, seqlen=2, nsamples=1)
+ ar = AutoRound(
+ tiny_opt_model_path, bits=bits, group_size=group_size, sym=sym, iters=0, seqlen=2, nsamples=1
+ )
ar.quantize_and_save(format="auto_round", output_dir=self.save_folder)
- # TODO when ark is ready, uncomment the following lines to do inference test
-
- # model = AutoModelForCausalLM.from_pretrained(
- # self.save_folder,
- # torch_dtype="auto",
- # device_map="auto",
- # )
+ model = AutoModelForCausalLM.from_pretrained(
+ self.save_folder,
+ torch_dtype="auto",
+ device_map="auto",
+ )
- # tokenizer = AutoTokenizer.from_pretrained(self.save_folder)
- # model_infer(model, tokenizer)
- shutil.rmtree(self.save_folder, ignore_errors=True)
+ tokenizer = AutoTokenizer.from_pretrained(self.save_folder)
+ model_infer(model, tokenizer)
- def test_asym_bits(self):
- model_name = self.model_name
+ def test_asym_bits(self, tiny_opt_model_path):
for bits in [2, 8]:
- model = AutoModelForCausalLM.from_pretrained(model_name, dtype="auto")
- tokenizer = AutoTokenizer.from_pretrained(model_name)
group_size, sym = 128, False
- ar = AutoRound(model, tokenizer, bits=bits, group_size=group_size, sym=sym, iters=0, seqlen=2, nsamples=1)
+ ar = AutoRound(
+ tiny_opt_model_path, bits=bits, group_size=group_size, sym=sym, iters=0, seqlen=2, nsamples=1
+ )
ar.quantize_and_save(format="auto_round", output_dir=self.save_folder)
- # TODO when ark is ready, uncomment the following lines to do inference test
+ model = AutoModelForCausalLM.from_pretrained(
+ self.save_folder,
+ torch_dtype="auto",
+ device_map="auto",
+ )
- # model = AutoModelForCausalLM.from_pretrained(
- # self.save_folder,
- # torch_dtype="auto",
- # device_map="auto",
- # )
-
- # tokenizer = AutoTokenizer.from_pretrained(self.save_folder)
- # model_infer(model, tokenizer)
- shutil.rmtree(self.save_folder, ignore_errors=True)
+ tokenizer = AutoTokenizer.from_pretrained(self.save_folder)
+ model_infer(model, tokenizer)
# use parameters later
- def test_asym_format(self):
- model_name = self.model_name
-
+ def test_asym_format(self, tiny_opt_model_path):
for format in ["auto_round", "auto_round:auto_gptq", "auto_round:gptqmodel"]:
- model = AutoModelForCausalLM.from_pretrained(model_name, dtype="auto")
- tokenizer = AutoTokenizer.from_pretrained(model_name)
bits, group_size, sym = 4, 128, False
- ar = AutoRound(model, tokenizer, bits=bits, group_size=group_size, sym=sym, iters=0, seqlen=2, nsamples=1)
- # TODO when ark is ready, uncomment the following lines to do inference test
+ ar = AutoRound(
+ tiny_opt_model_path,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=0,
+ seqlen=2,
+ nsamples=1,
+ disable_opt_rtn=True,
+ )
ar.quantize_and_save(format=format, output_dir=self.save_folder)
- # model = AutoModelForCausalLM.from_pretrained(
- # self.save_folder,
- # torch_dtype="auto",
- # device_map="auto",
- # )
+ model = AutoModelForCausalLM.from_pretrained(
+ self.save_folder,
+ torch_dtype="auto",
+ device_map="auto",
+ )
- # tokenizer = AutoTokenizer.from_pretrained(self.save_folder)
- # model_infer(model, tokenizer)
- shutil.rmtree(self.save_folder, ignore_errors=True)
+ tokenizer = AutoTokenizer.from_pretrained(self.save_folder)
+ model_infer(model, tokenizer)
diff --git a/test/test_cpu/quantization/test_block_fp.py b/test/test_cpu/quantization/test_block_fp.py
index 30b62e321..19625911e 100644
--- a/test/test_cpu/quantization/test_block_fp.py
+++ b/test/test_cpu/quantization/test_block_fp.py
@@ -12,18 +12,18 @@ from ...helpers import get_model_path
class TestAutoRoundBlockFP:
- @classmethod
- def setup_class(self):
- self.model_name = get_model_path("Qwen/Qwen2.5-1.5B-Instruct")
- self.save_dir = "./saved"
+ @pytest.fixture(autouse=True)
+ def setup_save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
@classmethod
- def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
+ def teardown_class(cls):
shutil.rmtree("runs", ignore_errors=True)
- def test_invalid_scheme(self):
- model_name = self.model_name
+ def test_invalid_scheme(self, tiny_qwen_model_path):
+ model_name = tiny_qwen_model_path
with pytest.raises(ValueError):
scheme = {
@@ -91,62 +91,3 @@ class TestAutoRoundBlockFP:
for j in range(N):
scale_ref[i, j] = data[i * 128 : (i + 1) * 128, j * 128 : (j + 1) * 128].abs().max() / max_val
assert (scale == scale_ref).all()
-
- def test_fp8_block_autoround_format(self):
- model_name = self.model_name
-
- scheme = "FP8_BLOCK"
- autoround = AutoRound(
- model_name,
- scheme=scheme,
- iters=2,
- seqlen=2,
- )
- quantized_model_path = self.save_dir
- compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
- tmp_layer = compressed_model.model.layers[1].self_attn.q_proj
- assert hasattr(tmp_layer, "weight_scale_inv")
- assert tmp_layer.weight.dtype is torch.float8_e4m3fn
- assert list(tmp_layer.weight_scale_inv.shape) == [12, 12]
- assert compressed_model.config.quantization_config["quant_method"] == "fp8"
- assert compressed_model.config.quantization_config["group_size"] == (128, 128)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- def test_fp8_block_fp8_format(self):
- model_name = self.model_name
-
- scheme = "FP8_BLOCK"
- autoround = AutoRound(
- model_name,
- scheme=scheme,
- iters=2,
- seqlen=2,
- )
- quantized_model_path = self.save_dir
- compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="fp8")
- tmp_layer = compressed_model.model.layers[1].self_attn.q_proj
- assert hasattr(tmp_layer, "weight_scale_inv")
- assert tmp_layer.weight.dtype is torch.float8_e4m3fn
- assert list(tmp_layer.weight_scale_inv.shape) == [12, 12]
- assert compressed_model.config.quantization_config["quant_method"] == "fp8"
- assert compressed_model.config.quantization_config["weight_block_size"] == (128, 128)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- def test_fp8_block_llm_compressor_format(self):
- model_name = self.model_name
-
- scheme = "FP8_BLOCK"
- autoround = AutoRound(
- model_name,
- scheme=scheme,
- iters=2,
- seqlen=2,
- )
- quantized_model_path = self.save_dir
- compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="llm_compressor")
- tmp_layer = compressed_model.model.layers[1].self_attn.q_proj
- assert hasattr(tmp_layer, "weight_scale")
- assert tmp_layer.weight.dtype is torch.float8_e4m3fn
- assert list(tmp_layer.weight_scale.shape) == [12, 12]
- assert compressed_model.config.quantization_config["quant_method"] == "compressed-tensors"
- shutil.rmtree(quantized_model_path, ignore_errors=True)
diff --git a/test/test_cpu/quantization/test_mix_bits.py b/test/test_cpu/quantization/test_mix_bits.py
index 062afb058..71a0dc1cd 100644
--- a/test/test_cpu/quantization/test_mix_bits.py
+++ b/test/test_cpu/quantization/test_mix_bits.py
@@ -25,16 +25,20 @@ def _get_folder_size(path: str) -> float:
class TestAutoRound:
+ @pytest.fixture(autouse=True)
+ def setup_save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
@classmethod
- def setup_class(self):
- self.model_name = opt_name_or_path
- self.save_dir = ".saved/"
- self.model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
- self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
+ def setup_class(cls):
+ cls.model_name = opt_name_or_path
+ cls.model = AutoModelForCausalLM.from_pretrained(cls.model_name, torch_dtype="auto", trust_remote_code=True)
+ cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name, trust_remote_code=True)
@classmethod
- def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
+ def teardown_class(cls):
shutil.rmtree("runs", ignore_errors=True)
@require_gptqmodel
@@ -65,7 +69,6 @@ class TestAutoRound:
assert model.model.model.decoder.layers[1].self_attn.v_proj.bits == 4
result = model.generate("Uncovering deep insights begins with")[0] # tokens
assert "!!!" not in model.tokenizer.decode(result) # string output
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_mixed_gptqmodel_convert_to_ar(self, dataloader):
layer_config = {
@@ -94,7 +97,6 @@ class TestAutoRound:
inputs = tokenizer(text, return_tensors="pt").to(model.device)
res = tokenizer.decode(model.generate(**inputs, max_new_tokens=5)[0])
print(res)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_mixed_autoround_format(self, dataloader):
layer_config = {
@@ -111,7 +113,7 @@ class TestAutoRound:
dataset=dataloader,
layer_config=layer_config,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
config_file = Path(quantized_model_path) / "config.json"
with open(config_file, "r", encoding="utf-8") as f:
@@ -130,7 +132,6 @@ class TestAutoRound:
text = "There is a girl who likes adventure,"
inputs = tokenizer(text, return_tensors="pt").to(model.device)
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_fallback_regex_for_awq_format(self, dataloader):
layer_config = {
@@ -145,7 +146,7 @@ class TestAutoRound:
dataset=dataloader,
layer_config=layer_config,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_awq")
quantization_config = AutoRoundConfig()
model = AutoModelForCausalLM.from_pretrained(
@@ -155,7 +156,6 @@ class TestAutoRound:
text = "There is a girl who likes adventure,"
inputs = tokenizer(text, return_tensors="pt").to(model.device)
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_mixed_ar_format_part_name_hf_loading(self, dataloader):
layer_config = {
@@ -171,7 +171,7 @@ class TestAutoRound:
dataset=dataloader,
layer_config=layer_config,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize()
autoround.save_quantized(output_dir=quantized_model_path, format="auto_round")
# remove old extra_config(which contains full name layer configs), only test regex config loading
@@ -203,7 +203,6 @@ class TestAutoRound:
text = "There is a girl who likes adventure,"
inputs = tokenizer(text, return_tensors="pt").to(model.device)
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_mixed_MXFP_autoround_format_loading(self, dataloader):
layer_config = {
@@ -229,4 +228,3 @@ class TestAutoRound:
tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
evaluate_accuracy(model, tokenizer, threshold=0.14, batch_size=16, limit=10)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
diff --git a/test/test_cpu/quantization/test_mxfp_nvfp.py b/test/test_cpu/quantization/test_mxfp_nvfp.py
index 54081839e..fb8d51c84 100644
--- a/test/test_cpu/quantization/test_mxfp_nvfp.py
+++ b/test/test_cpu/quantization/test_mxfp_nvfp.py
@@ -24,13 +24,14 @@ def _get_folder_size(path: str) -> float:
class TestAutoRoundFP:
- @classmethod
- def setup_class(self):
- self.save_dir = "./saved"
+ @pytest.fixture(autouse=True)
+ def setup_save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
@classmethod
- def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
+ def teardown_class(cls):
shutil.rmtree("runs", ignore_errors=True)
def test_nvfp4_moe_actmax_rtn(self, tiny_deepseek_v2_model_path, dataloader):
@@ -56,7 +57,6 @@ class TestAutoRoundFP:
compressed_model, _ = autoround.quantize()
moe = compressed_model.model.layers[1].mlp
assert hasattr(moe.experts[0].gate_proj.orig_layer, "act_max")
- shutil.rmtree(self.save_dir, ignore_errors=True)
def test_nvfp4_moe_actmax_ar(self, tiny_deepseek_v2_model_path, dataloader):
model_name = tiny_deepseek_v2_model_path
@@ -89,7 +89,6 @@ class TestAutoRoundFP:
), "Illegal NVFP4 packing for lm_head layer"
quantized_model_path = self.save_dir
assert is_model_outputs_similar(model_name, quantized_model_path)
- shutil.rmtree(self.save_dir, ignore_errors=True)
def test_mxfp4_moe_ar(self, tiny_deepseek_v2_model_path, dataloader):
model_name = tiny_deepseek_v2_model_path
@@ -118,7 +117,6 @@ class TestAutoRoundFP:
and hasattr(lm_head, "weight_packed")
and lm_head.weight_scale.dtype is torch.uint8
), "Illegal MXFP4 packing for lm_head layer"
- shutil.rmtree(self.save_dir, ignore_errors=True)
def test_mxfp4_llmcompressor_format(self, tiny_opt_model_path, dataloader):
model_name = tiny_opt_model_path
@@ -158,7 +156,6 @@ class TestAutoRoundFP:
and quantization_config["config_groups"]["group_0"]["weights"]["is_mx"] is True
and quantization_config["config_groups"]["group_0"]["weights"]["num_bits"] == 4
), f"Invalid MXFP4 quantization configuration: {quantization_config}"
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_rtn_mxfp4_llmcompressor_format(self, tiny_opt_model_path, dataloader):
model_name = tiny_opt_model_path
@@ -198,7 +195,6 @@ class TestAutoRoundFP:
and quantization_config["config_groups"]["group_0"]["weights"]["is_mx"] is True
and quantization_config["config_groups"]["group_0"]["weights"]["num_bits"] == 4
), f"Invalid MXFP4 quantization configuration: {quantization_config}"
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_mxfp8_llmcompressor_format(self, tiny_opt_model_path, dataloader):
model_name = tiny_opt_model_path
@@ -235,7 +231,6 @@ class TestAutoRoundFP:
assert (
0.05 < folder_size_gb < 0.1
), f"Quantized model folder size {folder_size_gb:.2f} GB is outside the expected range (0.05~0.1 GB)"
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_nvfp4_llmcompressor_format(self, tiny_opt_model_path, dataloader):
model_name = tiny_opt_model_path
@@ -272,7 +267,6 @@ class TestAutoRoundFP:
assert (
0.05 < folder_size_gb < 0.1
), f"Quantized model folder size {folder_size_gb:.2f} GB is outside the expected range (0.05~0.1 GB)"
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_nvfp4_autoround_format(self, tiny_opt_model_path, dataloader):
model_name = tiny_opt_model_path
@@ -297,7 +291,6 @@ class TestAutoRoundFP:
and tmp_layer.weight_scale.dtype is torch.float8_e4m3fn
and tmp_layer.weight_scale.shape[0] == 768
), "Illegal NVFP4 packing name or data_type or shape"
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_nvfp4_autoround_save_quantized(self, tiny_opt_model_path, dataloader):
model_name = tiny_opt_model_path
@@ -323,7 +316,6 @@ class TestAutoRoundFP:
and tmp_layer.weight_scale.dtype is torch.float8_e4m3fn
and tmp_layer.weight_scale.shape[0] == 768
), "Illegal NVFP4 packing name or data_type or shape"
- shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_qwen_moe_quant_infer(self, tiny_qwen_moe_model_path, dataloader):
model_name = tiny_qwen_moe_model_path
@@ -345,7 +337,6 @@ class TestAutoRoundFP:
quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, inplace=True, format="auto_round")
assert is_model_outputs_similar(model_name, quantized_model_path)
- shutil.rmtree(self.save_dir, ignore_errors=True)
@pytest.mark.parametrize(
"scheme, static_kv_dtype, static_attention_dtype",
@@ -410,4 +401,3 @@ class TestAutoRoundFP:
assert (
getattr(attn, "q_scale", None) is not None
), f"Missing q_scale in attention for scheme={scheme}, static_attention_dtype={static_attention_dtype}"
- shutil.rmtree(quantized_model_path, ignore_errors=True)
diff --git a/test/test_cpu/quantization/test_statc_attn.py b/test/test_cpu/quantization/test_statc_attn.py
index 8a133cc02..e5580f059 100644
--- a/test/test_cpu/quantization/test_statc_attn.py
+++ b/test/test_cpu/quantization/test_statc_attn.py
@@ -20,6 +20,7 @@ def setup_deepseekv2():
config = AutoConfig.from_pretrained(model_name, trust_remote_code=False)
config.num_hidden_layers = 1 # Reduce layers for testing
model = AutoModelForCausalLM.from_config(config)
+ model.config.name_or_path = None
output_dir = "./tmp/test_quantized_deepseekv2"
return model, tokenizer, output_dir, config
@@ -32,6 +33,7 @@ def setup_deepseekv3():
config = AutoConfig.from_pretrained(model_name, trust_remote_code=False)
config.num_hidden_layers = 1 # Reduce layers for testing
model = AutoModelForCausalLM.from_config(config)
+ model.config.name_or_path = None
output_dir = "./tmp/test_quantized_deepseekv3"
return model, tokenizer, output_dir, config
diff --git a/test/test_cpu/requirements.txt b/test/test_cpu/requirements.txt
index a6ce699a7..cb1723616 100644
--- a/test/test_cpu/requirements.txt
+++ b/test/test_cpu/requirements.txt
@@ -5,7 +5,10 @@ sentencepiece
torchvision
pillow
numba
+pytest
llmcompressor @ git+https://github.com/vllm-project/llm-compressor.git@main
lm_eval >= 0.4.10 # for transformers >= 5.0.0
diffusers
protobuf
+compressed-tensors==0.14.1a20260313 # temporary pin for llmcompressor
+transformers < 5.0.0
diff --git a/test/test_cpu/requirements_llmc.txt b/test/test_cpu/requirements_llmc.txt
new file mode 100644
index 000000000..b6f82d274
--- /dev/null
+++ b/test/test_cpu/requirements_llmc.txt
@@ -0,0 +1 @@
+llmcompressor @ git+https://github.com/vllm-project/llm-compressor.git@370c04c34191c0e5fb88cf889e16578bf8c7fe20
diff --git a/test/test_cpu/schemes/test_auto_scheme.py b/test/test_cpu/schemes/test_auto_scheme.py
index 9bd362bf3..ffcf6430e 100644
--- a/test/test_cpu/schemes/test_auto_scheme.py
+++ b/test/test_cpu/schemes/test_auto_scheme.py
@@ -7,19 +7,14 @@ from auto_round import AutoRound, AutoScheme
class TestAutoScheme:
- save_dir = "./saved"
-
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
+ @pytest.fixture(autouse=True)
+ def setup_save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
+ @classmethod
+ def teardown_class(self):
shutil.rmtree("runs", ignore_errors=True)
def test_auto_scheme_export(self, tiny_opt_model_path):
@@ -27,12 +22,10 @@ class TestAutoScheme:
scheme = AutoScheme(avg_bits=2, options=("W2A16"), nsamples=1, ignore_scale_zp_bits=True)
ar = AutoRound(model=model_name, scheme=scheme, iters=0, nsamples=1)
ar.quantize_and_save(self.save_dir)
- shutil.rmtree(self.save_dir, ignore_errors=True)
scheme = AutoScheme(avg_bits=4, options=("mxfp4"), nsamples=1, ignore_scale_zp_bits=True)
ar = AutoRound(model=model_name, scheme=scheme, iters=0, nsamples=1)
ar.quantize_and_save(self.save_dir)
- shutil.rmtree(self.save_dir, ignore_errors=True)
def test_layer_config(self, tiny_opt_model_path):
from auto_round.auto_scheme.utils import compute_avg_bits_for_model
diff --git a/test/test_cpu/schemes/test_auto_scheme_low_cpu_mem.py b/test/test_cpu/schemes/test_auto_scheme_low_cpu_mem.py
index 4776db7c0..deb06aafc 100644
--- a/test/test_cpu/schemes/test_auto_scheme_low_cpu_mem.py
+++ b/test/test_cpu/schemes/test_auto_scheme_low_cpu_mem.py
@@ -218,12 +218,14 @@ class TestAutoSchemeDataclassLowCpuMem:
class TestAutoSchemeIntegration:
"""Integration tests for AutoScheme with low_cpu_mem_usage."""
- save_dir = "./saved"
-
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
+ @pytest.fixture(autouse=True)
+ def setup_save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
yield
- shutil.rmtree("./saved", ignore_errors=True)
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
+ @classmethod
+ def teardown_class(self):
shutil.rmtree("runs", ignore_errors=True)
def test_auto_scheme_with_low_cpu_mem_disabled(self, tiny_opt_model_path):
diff --git a/test/test_cpu/schemes/test_scheme.py b/test/test_cpu/schemes/test_scheme.py
index 77ab5fd1f..8af28b7a5 100644
--- a/test/test_cpu/schemes/test_scheme.py
+++ b/test/test_cpu/schemes/test_scheme.py
@@ -1,21 +1,24 @@
+import os
import shutil
+import pytest
import transformers
from auto_round import AutoRound
from auto_round.schemes import QuantizationScheme
-from ...helpers import get_model_path, get_tiny_model, opt_name_or_path, qwen_name_or_path
+from ...helpers import get_model_path, get_tiny_model, opt_name_or_path, qwen_name_or_path, save_tiny_model
class TestAutoRound:
- @classmethod
- def setup_class(self):
- self.save_folder = "./saved"
+ @pytest.fixture(autouse=True)
+ def setup_save_folder(self, tmp_path):
+ self.save_folder = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_folder, ignore_errors=True)
@classmethod
def teardown_class(self):
- shutil.rmtree(self.save_folder, ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
def test_gguf(self, tiny_qwen_model_path, dataloader):
@@ -29,17 +32,14 @@ class TestAutoRound:
)
ar.quantize_and_save(self.save_folder, format="gguf:q4_k_m")
assert ar.bits == 4
- shutil.rmtree(self.save_folder, ignore_errors=True)
def test_w4a16(self, tiny_opt_model_path, dataloader):
ar = AutoRound(tiny_opt_model_path, scheme="W4A16", nsamples=1, iters=1, seqlen=2, dataset=dataloader)
assert ar.bits == 4
- ar.quantize()
def test_w2a16_rtn(self, tiny_opt_model_path, dataloader):
ar = AutoRound(tiny_opt_model_path, scheme="W2A16", nsamples=1, iters=0, seqlen=2, dataset=dataloader)
assert ar.bits == 2
- ar.quantize()
def test_w4a16_mixed(self, tiny_qwen_moe_model_path, dataloader):
@@ -56,14 +56,14 @@ class TestAutoRound:
low_cpu_mem_usage=False,
layer_config=layer_config,
)
- ar.quantize()
+ ar.quantize_and_save(self.save_folder)
assert ar.bits == 4
assert ar.model.model.layers[0].self_attn.q_proj.bits == 8
assert ar.model.model.layers[0].self_attn.k_proj.bits == 16
assert ar.model.model.layers[0].mlp.experts[0].up_proj.bits == 4
# assert ar.model.model.layers[0].mlp.shared_expert.gate_proj.bits == 8 # gate has been added to ignore_layers
-
- shutil.rmtree(self.save_folder, ignore_errors=True)
+ model = transformers.AutoModelForCausalLM.from_pretrained(self.save_folder, trust_remote_code=True)
+ assert model is not None, "Model loading failed after quantization with W4A16_MIXED scheme on MoE"
def test_w4a16_mixed_mllm(self, tiny_qwen_2_5_vl_model_path, dataloader):
@@ -74,14 +74,16 @@ class TestAutoRound:
batch_size=1,
iters=0,
seqlen=2,
+ disable_opt_rtn=True,
dataset=dataloader,
low_cpu_mem_usage=False,
)
- ar.quantize()
+ ar.quantize_and_save(self.save_folder)
+ model = transformers.Qwen2_5_VLForConditionalGeneration.from_pretrained(self.save_folder)
+ assert model is not None, "Model loading failed after quantization with W4A16_MIXED scheme on MLLM"
assert ar.bits == 4
- assert ar.model.language_model.layers[0].self_attn.q_proj.bits == 16
- assert ar.model.visual.blocks[0].attn.qkv.bits == 16
- shutil.rmtree(self.save_folder, ignore_errors=True)
+ assert ar.model.model.language_model.layers[0].self_attn.q_proj.bits == 16
+ assert ar.model.model.visual.blocks[0].attn.qkv.bits == 16
def test_mxfp4(self, tiny_opt_model_path, dataloader):
ar = AutoRound(tiny_opt_model_path, scheme="MXFP4", nsamples=1, iters=1, seqlen=2, dataset=dataloader)
@@ -89,9 +91,18 @@ class TestAutoRound:
assert ar.act_bits == 4
assert ar.data_type == "mx_fp"
assert ar.act_data_type == "mx_fp"
- ar.quantize()
- def test_vllm(self, tiny_qwen_vl_model_path):
+ def test_mxfp4_rceil(self, tiny_opt_model_path):
+ ar = AutoRound(tiny_opt_model_path, scheme="MXFP4_RCEIL", nsamples=1, iters=1)
+ assert ar.bits == 4
+ assert ar.act_bits == 4
+ assert ar.data_type == "mx_fp"
+ assert ar.act_data_type == "mx_fp_rceil"
+ ar.quantize_and_save()
+ model = transformers.AutoModelForCausalLM.from_pretrained("tmp_autoround", trust_remote_code=True)
+ assert model is not None, "Model loading failed after quantization with MXFP4 scheme"
+
+ def test_vlm(self, tiny_qwen_vl_model_path):
from auto_round import AutoRoundMLLM
ar = AutoRoundMLLM(tiny_qwen_vl_model_path, scheme="W2A16", nsamples=1, iters=1, seqlen=2)
@@ -104,20 +115,18 @@ class TestAutoRound:
assert ar.act_bits == 4
assert ar.data_type == "nv_fp"
assert ar.act_data_type == "nv_fp4_with_static_gs"
- ar.quantize()
-
- def test_all_scheme(self, tiny_opt_model_path, tiny_qwen_model_path, dataloader):
- import copy
-
- preset_schemes = ["W8A16", "MXFP8", "FPW8A16", "FP8_STATIC", "GGUF:Q2_K_S", "GGUF:Q4_K_M"]
- for scheme in preset_schemes:
- model_name = tiny_opt_model_path
- if "gguf" in scheme.lower():
- model_name = tiny_qwen_model_path
- print(f"scheme={scheme}")
- ar = AutoRound(model_name, scheme=scheme, nsamples=1, iters=1, seqlen=2, dataset=dataloader)
- ar.quantize_and_save(self.save_folder)
- shutil.rmtree(self.save_folder, ignore_errors=True)
+ ar.quantize_and_save(self.save_folder)
+ model = transformers.AutoModelForCausalLM.from_pretrained(self.save_folder, trust_remote_code=True)
+ assert model is not None, "Model loading failed after quantization with NVFP4 scheme"
+
+ @pytest.mark.parametrize(
+ "scheme", ["W8A16", "MXFP8", "FPW8A16", "FP8_BLOCK", "FP8_STATIC", "GGUF:Q2_K_S", "GGUF:Q4_K_M"]
+ )
+ def test_all_scheme(self, scheme, tiny_qwen_model_path, dataloader):
+ model_name = tiny_qwen_model_path
+ print(f"scheme={scheme}")
+ ar = AutoRound(model_name, scheme=scheme, nsamples=1, iters=1, seqlen=2, dataset=dataloader)
+ ar.quantize_and_save(self.save_folder)
def test_scheme_in_layer_config(self, dataloader):
model = get_tiny_model(opt_name_or_path, num_layers=5)
@@ -138,7 +147,7 @@ class TestAutoRound:
dataset=dataloader,
)
- ar.quantize()
+ ar.quantize_and_save(self.save_folder)
for n, m in ar.model.named_modules():
if n == "model.decoder.layers.2.self_attn.q_proj":
assert m.bits == 2
@@ -170,7 +179,7 @@ class TestAutoRound:
iters=0,
seqlen=2,
)
- ar.quantize()
+ ar.quantize_and_save(self.save_folder)
from auto_round.schemes import QuantizationScheme
@@ -185,4 +194,28 @@ class TestAutoRound:
disable_opt_rtn=True,
seqlen=2,
)
- ar.quantize()
+ ar.quantize_and_save(self.save_folder)
+
+ def test_fp8_static(self, tiny_opt_model_path):
+ ar = AutoRound(tiny_opt_model_path, scheme="FP8_STATIC", nsamples=1, iters=1)
+ assert ar.bits == 8
+ assert ar.act_bits == 8
+ assert ar.data_type == "fp"
+ assert ar.act_data_type == "fp"
+ assert ar.group_size == -1
+ assert ar.act_dynamic is False
+ ar.quantize_and_save()
+ model = transformers.AutoModelForCausalLM.from_pretrained("tmp_autoround", trust_remote_code=True)
+ assert model is not None, "Model loading failed after quantization with FP8_STATIC scheme"
+
+ def test_fp8_static_rtn(self, tiny_opt_model_path):
+ ar = AutoRound(tiny_opt_model_path, scheme="FP8_STATIC", nsamples=1, iters=0, disable_opt_rtn=True)
+ assert ar.bits == 8
+ assert ar.act_bits == 8
+ assert ar.data_type == "fp"
+ assert ar.act_data_type == "fp"
+ assert ar.group_size == -1
+ assert ar.act_dynamic is False
+ ar.quantize_and_save(self.save_folder)
+ model = transformers.AutoModelForCausalLM.from_pretrained(self.save_folder, trust_remote_code=True)
+ assert model is not None, "Model loading failed after quantization with FP8_STATIC scheme"
diff --git a/test/test_cpu/utils/test_calib_dataset.py b/test/test_cpu/utils/test_calib_dataset.py
index db016f6c7..adc129f8d 100644
--- a/test/test_cpu/utils/test_calib_dataset.py
+++ b/test/test_cpu/utils/test_calib_dataset.py
@@ -12,31 +12,34 @@ from ...helpers import get_model_path, opt_name_or_path
class TestLocalCalibDataset:
- @classmethod
- def setup_class(self):
+ @pytest.fixture(autouse=True)
+ def setup_save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ os.makedirs(self.save_dir, exist_ok=True)
+
json_data = [{"text": "awefdsfsddfd"}, {"text": "fdfdfsdfdfdfd"}, {"text": "dfdsfsdfdfdfdf"}]
- os.makedirs("./saved", exist_ok=True)
- self.json_file = "./saved/tmp.json"
+ self.json_file = os.path.join(self.save_dir, "tmp.json")
with open(self.json_file, "w") as json_file:
json.dump(json_data, json_file, indent=4)
jsonl_data = [{"text": "哈哈,開心點"}, {"text": "hello world"}]
- os.makedirs("./saved", exist_ok=True)
- self.jsonl_file = "./saved/tmp.jsonl"
+ self.jsonl_file = os.path.join(self.save_dir, "tmp.jsonl")
with open(self.jsonl_file, "w") as jsonl_file:
for item in jsonl_data:
json.dump(item, jsonl_file, ensure_ascii=False)
jsonl_file.write("\n")
- model_name = opt_name_or_path
- self.model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
- self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
+ @classmethod
+ def teardown_class(self):
+ shutil.rmtree("runs", ignore_errors=True)
- def test_json(self):
+ def test_json(self, tiny_opt_model_path):
bits, group_size, sym = 4, 128, True
autoround = AutoRound(
- self.model,
- self.tokenizer,
+ tiny_opt_model_path,
bits=bits,
group_size=group_size,
sym=sym,
@@ -46,11 +49,10 @@ class TestLocalCalibDataset:
)
autoround.quantize()
- def test_jsonl(self):
+ def test_jsonl(self, tiny_opt_model_path):
bits, group_size, sym = 4, 128, True
autoround = AutoRound(
- self.model,
- self.tokenizer,
+ tiny_opt_model_path,
bits=bits,
group_size=group_size,
sym=sym,
@@ -60,8 +62,8 @@ class TestLocalCalibDataset:
)
autoround.quantize()
- def test_apply_chat_template(self):
- model_name = get_model_path("Qwen/Qwen2.5-0.5B-Instruct")
+ def test_apply_chat_template(self, tiny_qwen_model_path):
+ model_name = tiny_qwen_model_path
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
dataset = "NeelNanda/pile-10k:apply_chat_template:system_prompt=''"
@@ -79,12 +81,11 @@ class TestLocalCalibDataset:
)
autoround.quantize()
- def test_combine_dataset(self):
+ def test_combine_dataset(self, tiny_qwen_model_path):
dataset = "NeelNanda/pile-10k" + "," + "madao33/new-title-chinese" + "," + "mbpp"
bits, group_size, sym = 4, 128, True
autoround = AutoRound(
- self.model,
- self.tokenizer,
+ tiny_qwen_model_path,
bits=bits,
group_size=group_size,
sym=sym,
@@ -95,12 +96,11 @@ class TestLocalCalibDataset:
)
autoround.quantize()
- def test_combine_dataset2(self):
+ def test_combine_dataset2(self, tiny_opt_model_path):
dataset = "NeelNanda/pile-10k:num=256,mbpp:num=256"
bits, group_size, sym = 4, 128, True
autoround = AutoRound(
- self.model,
- self.tokenizer,
+ tiny_opt_model_path,
bits=bits,
group_size=group_size,
sym=sym,
@@ -110,16 +110,3 @@ class TestLocalCalibDataset:
nsamples=1,
)
autoround.quantize()
-
- # def test_pile_val_backup_dataset(self):
- # dataset = "swift/pile-val-backup"
- # bits, group_size, sym = 4, 128, True
- # autoround = AutoRound(
- # self.model, self.tokenizer, bits=bits, group_size=group_size, sym=sym, iters=2, seqlen=128, dataset=dataset
- # )
- # autoround.quantize()
-
- @classmethod
- def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
diff --git a/test/test_cpu/utils/test_cli_usage.py b/test/test_cpu/utils/test_cli_usage.py
index e444524ae..6b84cad60 100644
--- a/test/test_cpu/utils/test_cli_usage.py
+++ b/test/test_cpu/utils/test_cli_usage.py
@@ -2,6 +2,8 @@ import os
import shutil
import sys
+import pytest
+
from auto_round.utils import parse_layer_config_arg
from ...helpers import get_model_path
@@ -11,16 +13,15 @@ AUTO_ROUND_PATH = "/".join(AUTO_ROUND_PATH[: AUTO_ROUND_PATH.index("test")])
class TestAutoRoundCmd:
-
- @classmethod
- def setup_class(self):
- pass
+ @pytest.fixture(autouse=True)
+ def setup_save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
@classmethod
def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
- shutil.rmtree("../../saved", ignore_errors=True)
shutil.rmtree("../../tmp_autoround", ignore_errors=True)
def test_auto_round_cmd(self, tiny_opt_model_path, tiny_qwen_vl_model_path):
@@ -32,7 +33,7 @@ class TestAutoRoundCmd:
assert False, "cmd line test fail, please have a check"
res = os.system(
- f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round --model {tiny_opt_model_path} --seqlen 32 --iter 2 --nsamples 1 --format auto_gptq,auto_round --output_dir ./saved --tasks piqa"
+ f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round --model {tiny_opt_model_path} --seqlen 32 --iter 2 --nsamples 1 --format auto_gptq,auto_round --output_dir {self.save_dir} --tasks piqa"
)
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
@@ -44,7 +45,7 @@ class TestAutoRoundCmd:
assert False, "cmd line test fail, please have a check"
res = os.system(
- f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -c 'from auto_round.__main__ import run_light; run_light()' --seqlen 8 --iter 2 --nsamples 8 --output_dir ./saved --tasks lambada_openai"
+ f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -c 'from auto_round.__main__ import run_light; run_light()' --seqlen 8 --iter 2 --nsamples 8 --output_dir {self.save_dir} --tasks lambada_openai"
)
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
@@ -62,14 +63,14 @@ class TestAutoRoundCmd:
assert False, "cmd line test fail, please have a check"
res = os.system(
- f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round --mllm --model {tiny_qwen_vl_model_path} --iter 2 --nsamples 2 --seqlen 32 --format auto_round --output_dir ./saved"
+ f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round --mllm --model {tiny_qwen_vl_model_path} --iter 2 --nsamples 2 --seqlen 32 --format auto_round --output_dir {self.save_dir}"
)
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
res = os.system(
f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round --mllm --iter 2 --nsamples 2 --model {tiny_qwen_vl_model_path} --seqlen 32 --format auto_round"
- " --quant_nontext_module --output_dir ./saved "
+ f" --quant_nontext_module --output_dir {self.save_dir} "
)
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
@@ -81,7 +82,7 @@ class TestAutoRoundCmd:
res = os.system(
f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round"
f" --model {tiny_opt_model_path} --seqlen 8 --iter 0 --disable_opt_rtn"
- f" --layer_config '{layer_cfg}' --format auto_round --output_dir ./saved"
+ f" --layer_config '{layer_cfg}' --format auto_round --output_dir {self.save_dir}"
)
if res > 0 or res == -1:
assert False, "cmd line test with --layer_config fail, please have a check"
diff --git a/test/test_cpu/utils/test_generation.py b/test/test_cpu/utils/test_generation.py
index 8cfc199d2..448c3cc40 100644
--- a/test/test_cpu/utils/test_generation.py
+++ b/test/test_cpu/utils/test_generation.py
@@ -11,16 +11,20 @@ from ...helpers import opt_name_or_path
class TestAutoRoundFormatGeneration:
+ @pytest.fixture(autouse=True)
+ def setup_save_folder(self, tmp_path):
+ self.save_folder = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_folder, ignore_errors=True)
+
@classmethod
def setup_class(self):
self.model_name = opt_name_or_path
self.model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
- self.save_folder = "./saved"
@classmethod
def teardown_class(self):
- shutil.rmtree(self.save_folder, ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
def test_4bits_sym(self, dataloader):
@@ -72,7 +76,7 @@ class TestAutoRoundFormatGeneration:
seqlen=2,
dataset=dataloader,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_folder
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
@@ -85,4 +89,3 @@ class TestAutoRoundFormatGeneration:
res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
print(res)
assert "!!!" not in res
- shutil.rmtree(self.save_folder, ignore_errors=True)
diff --git a/test/test_cpu/utils/test_model_scope.py b/test/test_cpu/utils/test_model_scope.py
index b53b73ada..18980225c 100644
--- a/test/test_cpu/utils/test_model_scope.py
+++ b/test/test_cpu/utils/test_model_scope.py
@@ -11,10 +11,14 @@ from ...helpers import get_model_path
class TestModelScope:
+ @pytest.fixture(autouse=True)
+ def setup_saved_path(self, tmp_path):
+ self.saved_path = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.saved_path, ignore_errors=True)
+
@classmethod
def setup_class(self):
- self.saved_path = "./saved"
-
self.source_path, self.cache_path = "/tf_dataset/auto_round/modelscope", "/home/hostuser/.cache/modelscope"
if os.path.exists(self.source_path):
if not os.path.exists("/home/hostuser/.cache"):
@@ -23,7 +27,6 @@ class TestModelScope:
@classmethod
def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
if os.path.exists(self.cache_path):
shutil.rmtree(self.cache_path, ignore_errors=True)
diff --git a/test/test_cuda/advanced/test_evaluation.py b/test/test_cuda/advanced/test_evaluation.py
index 16d991cb9..8f6c354b2 100644
--- a/test/test_cuda/advanced/test_evaluation.py
+++ b/test/test_cuda/advanced/test_evaluation.py
@@ -12,14 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""
-GPU tests for VLLM evaluation functionality.
-Tests the eval_with_vllm function and custom vllm_args parameter parsing.
-Validates accuracy thresholds for quantized models.
-
-Run with: pytest test/test_cuda/advanced/test_evaluation.py -v
-"""
-
import os
import sys
@@ -27,48 +19,6 @@ import pytest
from ...helpers import opt_name_or_path
-# Test models for vllm evaluation
-VLLM_EVAL_MODELS = [
- "OPEA/Qwen2.5-0.5B-Instruct-int4-sym-inc", # auto_round:auto_gptq format
-]
-
-
- not os.path.exists("/usr/bin/nvidia-smi") and not os.path.exists("/usr/local/cuda"), reason="CUDA not available"
-)
-class TestVllmEvaluation:
- """Test VLLM backend evaluation functionality."""
-
- @pytest.mark.parametrize("model", VLLM_EVAL_MODELS)
- def test_vllm_backend_with_custom_args(self, model):
- """Test vllm backend evaluation with custom vllm_args parameter."""
- python_path = sys.executable
-
- os.environ["VLLM_SKIP_WARMUP"] = "true"
- os.environ["NCCL_ASYNC_ERROR_HANDLING"] = "1"
- os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
-
- # Test with custom vllm_args
- cmd = f"{python_path} -m auto_round --model {model} --eval --tasks lambada_openai --eval_bs 128 --eval_backend vllm --limit 100 --vllm_args tensor_parallel_size=1,gpu_memory_utilization=0.6,max_model_len=2048"
-
- ret = os.system(cmd)
-
- assert ret == 0, f"vllm evaluation with custom args failed (rc={ret})"
-
- def test_vllm_backend_with_quantization_iters_0(self):
- """Test vllm evaluation with iters=0 (quantization without fine-tuning)."""
- python_path = sys.executable
-
- os.environ["VLLM_SKIP_WARMUP"] = "true"
- os.environ["NCCL_ASYNC_ERROR_HANDLING"] = "1"
- os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
-
- cmd = f"{python_path} -m auto_round --model {opt_name_or_path} --iters 0 --disable_opt_rtn --tasks lambada_openai --eval_bs 8 --eval_backend vllm --limit 100"
-
- ret = os.system(cmd)
-
- assert ret == 0, f"vllm evaluation with iters=0 failed (rc={ret})"
-
@pytest.mark.skipif(
not os.path.exists("/usr/bin/nvidia-smi") and not os.path.exists("/usr/local/cuda"), reason="CUDA not available"
@@ -76,17 +26,17 @@ class TestVllmEvaluation:
class TestHFEvaluation:
"""Test different evaluation modes: --eval and --eval_backend."""
- @pytest.mark.parametrize("model", VLLM_EVAL_MODELS)
- def test_eval_mode_hf_backend(self, model):
+ def test_eval_mode_hf_backend(self, tiny_opt_model_path):
"""Test --eval flag: evaluate model without quantization (HF backend default)."""
python_path = sys.executable
- cmd = f"{python_path} -m auto_round --model {model} --eval --tasks lambada_openai --limit 100"
+ cmd = f"{python_path} -m auto_round --model {tiny_opt_model_path} --eval --tasks lambada_openai --limit 10"
ret = os.system(cmd)
assert ret == 0, f"HF backend evaluation failed (rc={ret})"
+ @pytest.mark.skip_ci(reason="The evaluation is time-consuming")
def test_iters_0_hf_backend(self, tiny_opt_model_path):
"""Test quantization with iters=0 and HF backend evaluation."""
python_path = sys.executable
@@ -97,6 +47,7 @@ class TestHFEvaluation:
assert ret == 0, f"HF backend with iters=0 failed (rc={ret})"
+ @pytest.mark.skip_ci(reason="The evaluation is time-consuming")
def test_iters_0_task_by_task(self, tiny_opt_model_path):
"""Test quantization with iters=0 and task-by-task evaluation."""
python_path = sys.executable
diff --git a/test/test_cuda/advanced/test_fp8_input.py b/test/test_cuda/advanced/test_fp8_input.py
deleted file mode 100644
index 209ff8973..000000000
--- a/test/test_cuda/advanced/test_fp8_input.py
+++ /dev/null
@@ -1,147 +0,0 @@
-import os
-import shutil
-
-import pytest
-import torch
-from packaging import version
-from transformers import AutoModelForCausalLM, AutoTokenizer
-
-from auto_round import AutoRound
-from auto_round.utils import llm_load_model
-from auto_round.utils.weight_handler import (
- ModuleWeightType,
- check_and_mark_quantized_module,
- convert_module_to_hp_if_necessary,
-)
-
-from ...helpers import evaluate_accuracy, generate_prompt, get_model_path, get_tiny_model, transformers_version
-
-
-class TestAutoRound:
- save_dir = "./saved"
-
- def tiny_fp8_model(self):
- model_name = get_model_path("qwen/Qwen3-0.6B-FP8")
- model, tokenizer = llm_load_model(model_name)
- model.model.layers = model.model.layers[:3]
- return model, tokenizer
-
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
- yield
-
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- def test_small_model_rtn_generation(self, mock_fp8_capable_device):
- model, tokenizer = self.tiny_fp8_model()
- ar = AutoRound(model=model, tokenizer=tokenizer, iters=0)
- ar.quantize_and_save(output_dir=self.save_dir)
- model = AutoModelForCausalLM.from_pretrained(self.save_dir, torch_dtype="auto", trust_remote_code=True)
- tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- generate_prompt(model, tokenizer)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- def test_gguf_imatrix(self, mock_fp8_capable_device):
- model, tokenizer = self.tiny_fp8_model()
- ar = AutoRound(model=model, tokenizer=tokenizer, iters=0)
- ar.quantize_and_save(format="gguf:q2_k_s", output_dir=self.save_dir)
- # from llama_cpp import Llama
- #
- # gguf_file = os.listdir("saved/Qwen3-0.6B-FP8/-gguf")[0]
- # llm = Llama(f"saved/Qwen2.5-0.5B-Instruct-gguf/{gguf_file}", n_gpu_layers=-1)
- # output = llm("There is a girl who likes adventure,", max_tokens=32)
- # print(output)
- # shutil.rmtree("./saved", ignore_errors=True)
- # model = AutoModelForCausalLM.from_pretrained(self.save_dir, torch_dtype="auto", trust_remote_code=True)
- # tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- # text = "There is a girl who likes adventure,"
- # inputs = tokenizer(text, return_tensors="pt").to(model.device)
- # print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
-
- def test_small_model_rtn(self, mock_fp8_capable_device):
- model_name = get_model_path("qwen/Qwen3-0.6B-FP8")
- ar = AutoRound(model=model_name, iters=0)
- _, folder = ar.quantize_and_save(output_dir=self.save_dir)
- evaluate_accuracy(self.save_dir, threshold=0.25)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- def test_small_model_iters1(self, mock_fp8_capable_device):
- model_name = get_model_path("qwen/Qwen3-0.6B-FP8")
- ar = AutoRound(model=model_name, iters=1)
- _, folder = ar.quantize_and_save(output_dir=self.save_dir)
- evaluate_accuracy(self.save_dir, threshold=0.25)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- def test_medium_model_rtn(self, mock_fp8_capable_device):
- model_name = get_model_path("qwen/Qwen3-0.6B-FP8")
- ar = AutoRound(model=model_name, iters=0)
- _, folder = ar.quantize_and_save(output_dir=self.save_dir)
- evaluate_accuracy(self.save_dir, threshold=0.33)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- def test_medium_model_rtn_with_lm_head(self, mock_fp8_capable_device):
- model_name = get_model_path("qwen/Qwen3-0.6B-FP8")
- layer_config = {"lm_head": {"bits": 4}}
- ar = AutoRound(model=model_name, iters=0, layer_config=layer_config)
- _, folder = ar.quantize_and_save(output_dir=self.save_dir)
- evaluate_accuracy(self.save_dir, threshold=0.33)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- def test_fp8_model_gguf(self, mock_fp8_capable_device):
- from llama_cpp import Llama
-
- model, tokenizer = self.tiny_fp8_model()
- ar = AutoRound(model=model, tokenizer=tokenizer, iters=0)
- ar.quantize_and_save(output_dir=self.save_dir, format="gguf:q4_0")
- for file in os.listdir(self.save_dir):
- if file.endswith(".gguf"):
- gguf_file = file
- llm = Llama(f"saved/{gguf_file}", n_gpu_layers=-1)
- output = llm("There is a girl who likes adventure,", max_tokens=32)
- print(output)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- model, tokenizer = self.tiny_fp8_model()
- ar = AutoRound(model=model, tokenizer=tokenizer, iters=1)
- ar.quantize_and_save(output_dir=self.save_dir, format="gguf:q3_k_s")
- for file in os.listdir(self.save_dir):
- if file.endswith(".gguf"):
- gguf_file = file
- llm = Llama(f"saved/{gguf_file}", n_gpu_layers=-1)
- output = llm("There is a girl who likes adventure,", max_tokens=32)
- print(output)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- @pytest.mark.skipif(
- transformers_version >= version.parse("5.0.0"),
- reason="We need this patch for fp8 model loading without dequantization."
- "https://github.com/intel/auto-round/blob/72e1cecb4a984db101e26700618266115029b9ac/test/test_cuda/quantization/test_mxfp_nvfp.py#L19C5-L19C25",
- )
- def test_diff_datatype(self, mock_fp8_capable_device):
- for scheme in ["NVFP4", "MXFP4"]:
- model_name = get_model_path("qwen/Qwen3-0.6B-FP8")
- for iters in [0, 1]:
- print(f"Testing scheme: {scheme}, iters: {iters}")
- ar = AutoRound(model_name, iters=iters, scheme=scheme)
- ar.quantize_and_save(output_dir=self.save_dir)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
-
-# requires GPU to load FP8Linear
-class TestFP8Linear:
- def test_fp8_input(self, mock_fp8_capable_device):
- model = get_tiny_model(get_model_path("qwen/Qwen3-0.6B-FP8"))
- assert (
- type(model.model.layers[0].mlp.up_proj).__name__ == "FP8Linear"
- ), "Model does not contain FP8Linear layers"
- detected_types = check_and_mark_quantized_module(model)
- assert ModuleWeightType.FP8 in detected_types
- model = convert_module_to_hp_if_necessary(model)
- assert type(model.model.layers[0].mlp.up_proj) is torch.nn.Linear, "FP8Linear layer was not converted to Linear"
diff --git a/test/test_cuda/advanced/test_multiple_card.py b/test/test_cuda/advanced/test_multiple_card.py
index 08f2b4676..ac6d0fb22 100644
--- a/test/test_cuda/advanced/test_multiple_card.py
+++ b/test/test_cuda/advanced/test_multiple_card.py
@@ -1,8 +1,10 @@
+import os
+import re
import shutil
+import sys
import pytest
import torch
-from lm_eval.utils import make_table # pylint: disable=E0401
from transformers import AutoModelForCausalLM, AutoTokenizer
from auto_round import AutoRound
@@ -10,11 +12,63 @@ from auto_round import AutoRound
from ...envs import multi_card, require_gptqmodel, require_greater_than_050
from ...helpers import evaluate_accuracy, get_model_path, get_tiny_model
+AUTO_ROUND_PATH = __file__.split("/")
+AUTO_ROUND_PATH = "/".join(AUTO_ROUND_PATH[: AUTO_ROUND_PATH.index("test")])
-# import os
-# os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"
+
[email protected]_ci(reason="multiple card test")
+class TestAutoRoundCli:
+ tasks = "lambada_openai"
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
+ @pytest.fixture(autouse=True, scope="class")
+ def setup_and_teardown_class(self):
+ # ===== SETUP (setup_class) =====
+ print("[Setup] Running before any test in class")
+
+ # Yield to hand control to the test methods
+ yield
+
+ # ===== TEARDOWN (teardown_class) =====
+ print("[Teardown] Running after all tests in class")
+ shutil.rmtree("runs", ignore_errors=True)
+
+ @multi_card
+ def test_multiple_card_calib(self, tiny_opt_model_path):
+ python_path = sys.executable
+
+ ##test llm script
+ res = os.system(
+ f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round --model {tiny_opt_model_path} --devices '0,1' --quant_lm_head --iters 1 --nsamples 1 --output_dir None"
+ )
+ if res > 0 or res == -1:
+ assert False, "cmd line test fail, please have a check"
+
+ @multi_card
+ def test_multiple_card_nvfp4(self, tiny_opt_model_path):
+ python_path = sys.executable
+
+ ##test llm script
+ res = os.system(
+ f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round --model {tiny_opt_model_path} --scheme NVFP4 --devices '0,1' --iters 1 --nsamples 1 --enable_torch_compile --low_gpu_mem_usage"
+ )
+ if res > 0 or res == -1:
+ assert False, "cmd line test fail, please have a check"
+
+
[email protected]_ci(reason="multiple card test")
class TestAutoRound:
- save_dir = "./saved"
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
@pytest.fixture(autouse=True, scope="class")
def setup_and_teardown_class(self):
@@ -26,13 +80,13 @@ class TestAutoRound:
# ===== TEARDOWN (teardown_class) =====
print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
+ shutil.rmtree("./tmp_autoround", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
@multi_card
@require_gptqmodel
def test_device_map_str(self):
- model_name = "/models/Qwen2-0.5B-Instruct"
+ model_name = get_model_path("Qwen/Qwen2-0.5B-Instruct")
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16)
tokenizer = AutoTokenizer.from_pretrained(model_name)
device_map = ".*q_proj:0,.*k_proj:cuda:0,v_proj:1,.*up_proj:1"
@@ -40,27 +94,6 @@ class TestAutoRound:
autoround.quantize()
autoround.save_quantized(self.save_dir, format="auto_round", inplace=False)
evaluate_accuracy(self.save_dir, threshold=0.45, batch_size="auto")
- shutil.rmtree("./saved", ignore_errors=True)
-
- @multi_card
- def test_layer_norm(self, tiny_opt_model_path):
- model = AutoModelForCausalLM.from_pretrained(tiny_opt_model_path, torch_dtype=torch.float16)
- tokenizer = AutoTokenizer.from_pretrained(tiny_opt_model_path)
- device_map = {"norm": "cuda:1"}
- autoround = AutoRound(
- model, tokenizer, iters=2, device_map=device_map, nsamples=7, seqlen=32, enable_norm_bias_tuning=True
- )
- autoround.quantize()
-
- @multi_card
- def test_rms_norm(self, tiny_qwen_model_path):
- model = AutoModelForCausalLM.from_pretrained(tiny_qwen_model_path, torch_dtype=torch.float16)
- tokenizer = AutoTokenizer.from_pretrained(tiny_qwen_model_path)
- device_map = {"norm": "cuda:1"}
- autoround = AutoRound(
- model, tokenizer, iters=2, device_map=device_map, nsamples=7, seqlen=32, enable_norm_bias_tuning=True
- )
- autoround.quantize()
@multi_card
def test_act_quantization(self, tiny_qwen_model_path):
@@ -70,221 +103,52 @@ class TestAutoRound:
autoround = AutoRound(
model, tokenizer, iters=2, device_map=device_map, nsamples=7, seqlen=32, act_bits=4, act_dynamic=False
)
- autoround.quantize()
-
- @multi_card
- def test_lm_head(self):
- model_path = get_model_path("qwen/Qwen2.5-7B-Instruct")
- model = get_tiny_model(model_path)
- tokenizer = AutoTokenizer.from_pretrained(model_path)
- device_map = {".*q_proj": "0", ".*k_proj": "cuda:1", "v_proj": 1, ".*up_proj": "1", "lm_head": 1}
- layer_config = {"lm_head": {"bits": 4}}
- autoround = AutoRound(
- model,
- tokenizer,
- iters=2,
- device_map=device_map,
- nsamples=7,
- seqlen=32,
- enable_norm_bias_tuning=True,
- layer_config=layer_config,
- )
- autoround.quantize()
-
- @multi_card
- def test_device_map(self, tiny_qwen_model_path):
- model = AutoModelForCausalLM.from_pretrained(tiny_qwen_model_path, torch_dtype=torch.float16)
- tokenizer = AutoTokenizer.from_pretrained(tiny_qwen_model_path)
- device_map = {".*q_proj": "0", ".*k_proj": "cuda:1", "v_proj": 1, ".*up_proj": "cpu"}
- autoround = AutoRound(model, tokenizer, iters=2, device_map=device_map, nsamples=7, seqlen=32)
- autoround.quantize()
-
- model_name = "OPEA/Meta-Llama-3.1-8B-Instruct-int4-sym-inc"
-
- device_map = {}
- for i in range(0, 32):
- key = f"model.layers.{str(i)}"
- device_map[key] = "cuda"
- device_map["model.layers.1"] = "cpu"
- device_map["model.layers.2"] = "cpu"
- device_map["model.layers.3"] = "cpu"
- device_map["model.layers.4"] = "cpu"
- device_map["model.layers.5"] = "cpu"
- device_map["model.layers.6"] = "cpu"
- device_map["model.layers.27"] = "cpu"
- device_map["model.layers.28"] = "cpu"
- device_map["model.layers.30"] = "cpu"
- device_map["model.layers.31"] = "cpu"
- device_map["lm_head"] = "cuda"
- device_map["model.norm"] = "cuda"
- device_map["model.rotary_emb"] = "cuda"
- device_map["model.embed_tokens"] = "cuda"
-
- device_map1 = {}
- for i in range(0, 32):
- key = f"model.layers.{str(i)}"
- device_map1[key] = "cuda"
- device_map1["model.layers.1"] = "cuda:1"
- device_map1["model.layers.2"] = "cuda:1"
- device_map1["model.layers.3"] = "cuda:1"
- device_map1["model.layers.4"] = "cuda:1"
- device_map1["model.layers.5"] = "cuda:1"
- device_map1["model.layers.6"] = "cuda:1"
- device_map1["model.layers.27"] = "cuda:1"
- device_map1["model.layers.28"] = "cuda:1"
- device_map1["model.layers.30"] = "cuda:1"
- device_map1["model.layers.31"] = "cuda:1"
- device_map1["lm_head"] = "cuda:1"
- device_map1["model.norm"] = "cuda"
- device_map1["model.rotary_emb"] = "cuda"
- device_map1["model.embed_tokens"] = "cuda"
-
- for tmp_device_map in [
- device_map1,
- device_map,
- None,
- 0,
- "balanced",
- "balanced_low_0",
- "sequential",
- "cpu",
- "cuda:0",
- "cuda",
- "auto",
- ]:
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map=tmp_device_map)
-
- tokenizer = AutoTokenizer.from_pretrained(model_name)
-
- prompts = [
- "Hello,my name is",
- # "The president of the United States is",
- # "The capital of France is",
- # "The future of AI is",
- ]
-
- texts = []
- for prompt in prompts:
- messages = [{"role": "user", "content": prompt}]
- text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
- texts.append(text)
-
- inputs = tokenizer(texts, return_tensors="pt", padding=False, truncation=True)
-
- outputs = model.generate(
- input_ids=inputs["input_ids"].to(model.device),
- attention_mask=inputs["attention_mask"].to(model.device),
- do_sample=False, ## change this to follow official usage
- max_new_tokens=5,
- )
- generated_ids = [
- output_ids[len(input_ids) :] for input_ids, output_ids in zip(inputs["input_ids"], outputs)
- ]
-
- decoded_outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
-
- for i, prompt in enumerate(prompts):
- print(f"Prompt: {prompt}")
- print(f"Generated: {decoded_outputs[i]}")
- print("-" * 50)
- model = None
- del model
- torch.cuda.empty_cache()
+ autoround.quantize_and_save()
@multi_card
- def test_device_map_dict(self, tiny_opt_model_path):
- device_map = {".*q_proj": "0", ".*k_proj": "cuda:1", "v_proj": 1, ".*up_proj": "1"}
- bits, group_size, sym = 4, 128, False
- model = AutoModelForCausalLM.from_pretrained(tiny_opt_model_path, torch_dtype=torch.float16, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(tiny_opt_model_path)
- autoround = AutoRound(
- model,
- tokenizer,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=2,
- seqlen=2,
- device_map=device_map,
- )
- autoround.quantize()
-
- # test model_name
+ def test_device_map_and_norm_bias_tuning(self, tiny_qwen_model_path):
+ device_map = {
+ ".*q_proj": "0",
+ ".*k_proj": "cuda:1",
+ "v_proj": 1,
+ ".*up_proj": "cpu",
+ "lm_head": 1,
+ "norm": "cuda:1",
+ }
autoround = AutoRound(
- tiny_opt_model_path,
- tokenizer,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=2,
- seqlen=2,
- device_map=device_map,
+ tiny_qwen_model_path, iters=2, device_map=device_map, nsamples=7, seqlen=32, enable_norm_bias_tuning=True
)
- autoround.quantize()
-
- # test rtn
- autoround = AutoRound(
- tiny_opt_model_path,
- tokenizer,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=0,
- seqlen=2,
- device_map=device_map,
- )
- autoround.quantize()
+ autoround.quantize_and_save()
@multi_card
@require_greater_than_050
def test_device_map_for_triton(self):
from transformers import AutoModelForCausalLM, AutoTokenizer
- model_name = "OPEA/Meta-Llama-3.1-8B-Instruct-int4-sym-inc"
+ model_name = "OPEA/Qwen2.5-0.5B-Instruct-int4-sym-inc"
device_map = {}
for i in range(0, 32):
key = f"model.layers.{str(i)}"
- device_map[key] = "cuda"
+ device_map[key] = "cuda:0"
device_map["model.layers.1"] = "cpu"
device_map["model.layers.2"] = "cpu"
device_map["model.layers.3"] = "cpu"
device_map["model.layers.4"] = "cpu"
device_map["model.layers.5"] = "cpu"
- device_map["model.layers.6"] = "cpu"
- device_map["model.layers.27"] = "cpu"
- device_map["model.layers.28"] = "cpu"
- device_map["model.layers.30"] = "cpu"
- device_map["model.layers.31"] = "cpu"
+ device_map["model.layers.6"] = "cuda:1"
+ device_map["model.layers.21"] = "cuda:1"
device_map["lm_head"] = "cuda"
device_map["model.norm"] = "cuda"
device_map["model.rotary_emb"] = "cuda"
device_map["model.embed_tokens"] = "cuda"
- device_map1 = {}
- for i in range(0, 32):
- key = f"model.layers.{str(i)}"
- device_map1[key] = "cuda"
- device_map1["model.layers.1"] = "cuda:1"
- device_map1["model.layers.2"] = "cuda:1"
- device_map1["model.layers.3"] = "cuda:1"
- device_map1["model.layers.4"] = "cuda:1"
- device_map1["model.layers.5"] = "cuda:1"
- device_map1["model.layers.6"] = "cuda:1"
- device_map1["model.layers.27"] = "cuda:1"
- device_map1["model.layers.28"] = "cuda:1"
- device_map1["model.layers.30"] = "cuda:1"
- device_map1["model.layers.31"] = "cuda:1"
- device_map1["lm_head"] = "cuda:1"
- device_map1["model.norm"] = "cuda"
- device_map1["model.rotary_emb"] = "cuda"
- device_map1["model.embed_tokens"] = "cuda"
from transformers import AutoRoundConfig
quantization_config = AutoRoundConfig(backend="tritonv2")
for tmp_device_map in [
- device_map1,
+ device_map,
0,
"balanced",
"balanced_low_0",
@@ -300,10 +164,7 @@ class TestAutoRound:
tokenizer = AutoTokenizer.from_pretrained(model_name)
prompts = [
- "Hello,my name is",
- # "The president of the United States is",
- # "The capital of France is",
- # "The future of AI is",
+ "The capital of France is",
]
texts = []
@@ -325,6 +186,7 @@ class TestAutoRound:
]
decoded_outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
+ assert "Paris" in decoded_outputs[0], f"Expected 'Paris' in the output, but got: {decoded_outputs[0]}"
for i, prompt in enumerate(prompts):
print(f"Prompt: {prompt}")
@@ -335,12 +197,11 @@ class TestAutoRound:
torch.cuda.empty_cache()
@multi_card
- def test_mllm_device_map(self):
- model_name = get_model_path("qwen/Qwen2-VL-2B-Instruct")
+ def test_mllm_device_map(self, tiny_qwen_2_5_vl_model_path):
from auto_round import AutoRoundMLLM
device_map = "0,1"
- ar = AutoRoundMLLM(model_name, device_map=device_map)
+ ar = AutoRoundMLLM(tiny_qwen_2_5_vl_model_path, device_map=device_map)
assert ar.device == "cuda:0"
assert ar.device_map == device_map
@@ -357,4 +218,4 @@ class TestAutoRound:
device_map = {"model.language_model.layers": 0, "model.visual.blocks": 1}
ar = AutoRoundMLLM(ar.model, ar.tokenizer, processor=ar.processor, device_map=device_map)
assert ar.model.model.language_model.layers[0].self_attn.q_proj.tuning_device == "cuda:0"
- assert ar.model.model.visual.blocks[0].mlp.fc1.tuning_device == "cuda:1"
+ assert ar.model.model.visual.blocks[0].mlp.gate_proj.tuning_device == "cuda:1"
diff --git a/test/test_cuda/advanced/test_multiple_card_calib.py b/test/test_cuda/advanced/test_multiple_card_calib.py
deleted file mode 100644
index e41e0cfd7..000000000
--- a/test/test_cuda/advanced/test_multiple_card_calib.py
+++ /dev/null
@@ -1,51 +0,0 @@
-import os
-import re
-import shutil
-import sys
-
-import pytest
-
-from ...envs import multi_card
-
-AUTO_ROUND_PATH = __file__.split("/")
-AUTO_ROUND_PATH = "/".join(AUTO_ROUND_PATH[: AUTO_ROUND_PATH.index("test")])
-
-
-class TestAutoRound:
- save_dir = "./saved"
- tasks = "lambada_openai"
-
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
- yield
-
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- @multi_card
- def test_multiple_card_calib(self):
- python_path = sys.executable
-
- ##test llm script
- res = os.system(
- f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round --model /models/Meta-Llama-3.1-8B-Instruct --devices '0,1' --quant_lm_head --iters 1 --nsamples 1 --output_dir None"
- )
- if res > 0 or res == -1:
- assert False, "cmd line test fail, please have a check"
-
- @multi_card
- def test_multiple_card_nvfp4(self):
- python_path = sys.executable
-
- ##test llm script
- res = os.system(
- f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {python_path} -m auto_round --model facebook/opt-125m --scheme NVFP4 --devices '0,1' --iters 1 --nsamples 1 --enable_torch_compile --low_gpu_mem_usage"
- )
- if res > 0 or res == -1:
- assert False, "cmd line test fail, please have a check"
diff --git a/test/test_cuda/core/__init__.py b/test/test_cuda/algorithms/__init__.py
similarity index 100%
rename from test/test_cuda/core/__init__.py
rename to test/test_cuda/algorithms/__init__.py
diff --git a/test/test_cuda/utils/test_alg_ext.py b/test/test_cuda/algorithms/test_alg_ext.py
similarity index 68%
rename from test/test_cuda/utils/test_alg_ext.py
rename to test/test_cuda/algorithms/test_alg_ext.py
index e599ec77a..17cbe6d90 100644
--- a/test/test_cuda/utils/test_alg_ext.py
+++ b/test/test_cuda/algorithms/test_alg_ext.py
@@ -14,21 +14,37 @@ AUTO_ROUND_PATH = "/".join(AUTO_ROUND_PATH[: AUTO_ROUND_PATH.index("test")])
class TestAlgExt:
- save_folder = "./saved"
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_folder = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_folder, ignore_errors=True)
@pytest.fixture(autouse=True, scope="class")
def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
yield
-
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ @pytest.mark.parametrize("scheme", ["MXFP4", "NVFP4", "W2A16G64", "gguf:q2_k_s,gguf:q4_k_s"])
+ def test_all_support_dtype(self, scheme, tiny_qwen_model_path):
+ from auto_round.auto_scheme import AutoScheme
+
+ avg_bits = 2 if scheme == "W2A16G64" else 4
+ scheme = AutoScheme(options=scheme, avg_bits=avg_bits, ignore_scale_zp_bits=True)
+ ar = AutoRound(
+ tiny_qwen_model_path,
+ scheme=scheme,
+ iters=1,
+ nsamples=1,
+ seqlen=32,
+ enable_alg_ext=True,
+ enable_torch_compile=True,
+ )
+ ar.quantize()
+
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @pytest.mark.skipif(reason="Time-consuming for accuracy evaluation")
def test_2bits(self):
model_name = get_model_path("facebook/opt-125m")
ar = AutoRound(model=model_name, bits=2, group_size=64, enable_alg_ext=True)
@@ -40,8 +56,8 @@ class TestAlgExt:
tokenizer = AutoTokenizer.from_pretrained(self.save_folder)
evaluate_accuracy(model, tokenizer, threshold=0.22, batch_size=64)
- shutil.rmtree(self.save_folder, ignore_errors=True)
+ @pytest.mark.skip_ci(reason="Not necessary to test all case in CI")
def test_cli(self, tiny_opt_model_path):
import os
@@ -58,20 +74,3 @@ class TestAlgExt:
)
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
-
- def test_all_support_dtype(self, tiny_qwen_model_path):
- from auto_round.auto_scheme import AutoScheme
-
- for scheme in ["MXFP4", "NVFP4", "W2A16G64", "gguf:q2_k_s,gguf:q4_k_s"]:
- avg_bits = 2 if scheme == "W2A16G64" else 4
- scheme = AutoScheme(options=scheme, avg_bits=avg_bits, ignore_scale_zp_bits=True)
- ar = AutoRound(
- tiny_qwen_model_path,
- scheme=scheme,
- iters=1,
- nsamples=1,
- seqlen=32,
- enable_alg_ext=True,
- enable_torch_compile=True,
- )
- ar.quantize()
diff --git a/test/test_cuda/schemes/test_auto_scheme.py b/test/test_cuda/algorithms/test_auto_scheme.py
similarity index 76%
rename from test/test_cuda/schemes/test_auto_scheme.py
rename to test/test_cuda/algorithms/test_auto_scheme.py
index 6d23b3de1..133284bfc 100644
--- a/test/test_cuda/schemes/test_auto_scheme.py
+++ b/test/test_cuda/algorithms/test_auto_scheme.py
@@ -15,19 +15,16 @@ from ...helpers import evaluate_accuracy, get_model_path, get_tiny_model
class TestAutoScheme:
- save_dir = "./saved"
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
@pytest.fixture(autouse=True, scope="class")
def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
yield
-
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
def test_gguf_k_0(self, tiny_qwen_model_path):
@@ -36,39 +33,48 @@ class TestAutoScheme:
ar = AutoRound(model=tiny_qwen_model_path, scheme=scheme, iters=1, enable_alg_ext=True)
ar.quantize_and_save(self.save_dir, format="gguf:q2_k_s")
+ @pytest.mark.skip_ci(reason="not necessary to test all options")
+ def test_auto_scheme_export_gguf(self, tiny_qwen_model_path):
+ scheme = AutoScheme(avg_bits=3, options=("gguf:q2_k_s,gguf:q4_k_s"), nsamples=1, ignore_scale_zp_bits=True)
+ ar = AutoRound(model=tiny_qwen_model_path, scheme=scheme, iters=0, disable_opt_rtn=True, nsamples=1)
+ ar.quantize()
+
+ @pytest.mark.skip_ci(reason="not necessary to test all options")
def test_gguf_k_1(self, tiny_qwen_model_path):
target_bits = 3.5
scheme = AutoScheme(avg_bits=target_bits, options=("GGUF:Q2_K_S", "GGUF:Q4_1"))
ar = AutoRound(model=tiny_qwen_model_path, scheme=scheme, iters=1, enable_alg_ext=True)
ar.quantize_and_save(self.save_dir, format="gguf:q2_k_s")
- #
+ @pytest.mark.skip_ci(reason="not necessary to test all options")
def test_embedding_fallback(self, tiny_qwen_model_path):
target_bits = 5.0
scheme = AutoScheme(avg_bits=target_bits, options=("GGUF:Q4_K_M", "GGUF:Q8_0"))
ar = AutoRound(model=tiny_qwen_model_path, scheme=scheme, iters=1, enable_alg_ext=True)
ar.quantize_and_save(self.save_dir, format="gguf:q2_k_s")
+ @pytest.mark.skip_ci(reason="not necessary to test all options")
def test_gguf_export(self, tiny_qwen_model_path):
target_bits = 3
scheme = AutoScheme(avg_bits=target_bits, options=("GGUF:Q2_K_S", "GGUF:Q4_K_M"), ignore_scale_zp_bits=True)
ar = AutoRound(model=tiny_qwen_model_path, scheme=scheme, iters=0)
ar.quantize_and_save(self.save_dir, format="gguf:q2_k_s")
+ @pytest.mark.skip_ci(reason="not necessary to test all options")
def test_gguf(self):
- model_name = get_model_path("qwen/Qwen3-8B")
+ model_name = get_model_path("Qwen/Qwen3-8B")
model = get_tiny_model(model_name)
tokenizer = transformers.AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
target_bits = 3
scheme = AutoScheme(avg_bits=target_bits, options=("GGUF:Q2_K_S", "GGUF:Q4_K_M"), ignore_scale_zp_bits=True)
- ar = AutoRound(model=model, tokenizer=tokenizer, scheme=scheme, iters=0, nsamples=1, disable_opt_rtn=True)
+ ar = AutoRound(model=model, tokenizer=tokenizer, scheme=scheme, iters=0, disable_opt_rtn=True, nsamples=1)
model, layer_config = ar.quantize()
avg_bits, _ = compute_avg_bits_for_model(model, ignore_scale_zp_bits=True)
print(avg_bits)
assert target_bits - 0.1 < avg_bits <= target_bits + 1e-3
- def test_shared_layers(self):
- model_name = get_model_path("facebook/opt-125m")
+ def test_shared_layers(self, tiny_opt_model_path):
+ model_name = tiny_opt_model_path
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained(model_name)
@@ -80,17 +86,17 @@ class TestAutoScheme:
from auto_round.auto_scheme.utils import parse_shared_layers
res = parse_shared_layers(model, shared_layers)
- assert len(res) == 24
+ assert len(res) == 4
assert [
- "model.decoder.layers.2.self_attn.out_proj",
- "model.decoder.layers.2.self_attn.q_proj",
- "model.decoder.layers.2.self_attn.v_proj",
+ "model.decoder.layers.1.self_attn.out_proj",
+ "model.decoder.layers.1.self_attn.q_proj",
+ "model.decoder.layers.1.self_attn.v_proj",
] in res
- assert ["model.decoder.layers.6.fc1", "model.decoder.layers.6.fc2"] in res
- assert ["model.decoder.layers.7.fc1", "model.decoder.layers.7.fc2"] in res
+ assert ["model.decoder.layers.0.fc1", "model.decoder.layers.0.fc2"] in res
+ assert ["model.decoder.layers.1.fc1", "model.decoder.layers.1.fc2"] in res
target_bits = 5.0
scheme = AutoScheme(avg_bits=target_bits, options=("W4A16", "MXFP8"), shared_layers=shared_layers)
- ar = AutoRound(model=model_name, scheme=scheme, iters=0, nsamples=1)
+ ar = AutoRound(model=model_name, scheme=scheme, iters=0, disable_opt_rtn=True, nsamples=1)
model, layer_config = ar.quantize()
avg_bits, _ = compute_avg_bits_for_model(model)
for names in res:
@@ -104,27 +110,35 @@ class TestAutoScheme:
bits = set(bits)
assert len(bits) == 1
print(avg_bits)
- assert target_bits - 0.1 < avg_bits <= target_bits + 1e-3
+ assert target_bits - 0.2 < avg_bits <= target_bits + 1e-3
- #
+ @pytest.mark.skip_ci(reason="multiple card test")
@multi_card
def test_multi_card(self, tiny_qwen_model_path):
target_bits = 4.5
for device_map in ["auto", "0,1", "0", None]:
scheme = AutoScheme(avg_bits=target_bits, options=("NVFP4"))
- ar = AutoRound(model=tiny_qwen_model_path, scheme=scheme, iters=0, nsamples=1, device_map=device_map)
+ ar = AutoRound(
+ model=tiny_qwen_model_path,
+ scheme=scheme,
+ iters=0,
+ disable_opt_rtn=True,
+ nsamples=1,
+ device_map=device_map,
+ )
model, layer_config = ar.quantize()
avg_bits, _ = compute_avg_bits_for_model(model)
print(avg_bits)
assert target_bits - 0.1 < avg_bits <= target_bits + 1e-3
+ @pytest.mark.skip_ci(reason="multiple card test")
@multi_card
def test_multi_card_1(self, tiny_qwen_model_path):
target_bits = 4.5
from transformers import AutoModelForCausalLM, AutoTokenizer
scheme = AutoScheme(avg_bits=target_bits, options=("NVFP4"))
- ar = AutoRound(model=tiny_qwen_model_path, scheme=scheme, iters=0, nsamples=1)
+ ar = AutoRound(model=tiny_qwen_model_path, scheme=scheme, iters=0, disable_opt_rtn=True, nsamples=1)
model, layer_config = ar.quantize()
avg_bits, _ = compute_avg_bits_for_model(model)
print(avg_bits)
@@ -135,48 +149,55 @@ class TestAutoScheme:
# for device_map in ["auto", "0,1", "0", None]:
scheme = AutoScheme(avg_bits=target_bits, options=("NVFP4"), low_gpu_mem_usage=False, device_map="auto")
- ar = AutoRound(model=tiny_qwen_model_path, scheme=scheme, iters=0, nsamples=1)
+ ar = AutoRound(model=tiny_qwen_model_path, scheme=scheme, iters=0, disable_opt_rtn=True, nsamples=1)
model, layer_config = ar.quantize()
avg_bits, _ = compute_avg_bits_for_model(model)
print(avg_bits)
assert target_bits - 0.1 < avg_bits <= target_bits + 1e-3
+ @pytest.mark.skip_ci(reason="multiple card test")
@multi_card
def test_dict_device_map(self, tiny_qwen_model_path):
target_bits = 8.25
device_map = {"up_proj": 0, "down_proj": 1}
scheme = AutoScheme(avg_bits=target_bits, options=("MXFP8"))
- ar = AutoRound(model=tiny_qwen_model_path, scheme=scheme, iters=0, nsamples=1, device_map=device_map)
+ ar = AutoRound(
+ model=tiny_qwen_model_path, scheme=scheme, iters=0, disable_opt_rtn=True, nsamples=1, device_map=device_map
+ )
model, layer_config = ar.quantize()
avg_bits, _ = compute_avg_bits_for_model(model)
print(avg_bits)
assert target_bits - 0.1 < avg_bits <= target_bits + 1e-3
+ @pytest.mark.skip_ci(reason="Not necessary to test the corner case in CI")
def test_min_target_bits(self, tiny_opt_model_path):
target_bits = 4.644
scheme = AutoScheme(avg_bits=target_bits, options=("MXFP4", "W8A16"))
- ar = AutoRound(model=tiny_opt_model_path, scheme=scheme, iters=0, nsamples=1)
+ ar = AutoRound(model=tiny_opt_model_path, scheme=scheme, iters=0, disable_opt_rtn=True, nsamples=1)
model, layer_config = ar.quantize()
avg_bits, _ = compute_avg_bits_for_model(model)
print(avg_bits)
assert target_bits - 0.1 < avg_bits <= target_bits + 1e-3
- #
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
def test_max_target_bits(self):
target_bits = 8.025
model_path = get_model_path("facebook/opt-125m")
scheme = AutoScheme(avg_bits=target_bits, options=("MXFP4", "W8A16"))
- ar = AutoRound(model=model_path, scheme=scheme, iters=0, nsamples=1)
+ ar = AutoRound(model=model_path, scheme=scheme, iters=0, disable_opt_rtn=True, nsamples=1)
model, layer_config = ar.quantize()
avg_bits, _ = compute_avg_bits_for_model(model)
print(avg_bits)
assert target_bits - 0.1 < avg_bits <= target_bits + 1e-3
+ @pytest.mark.skip_ci(reason="Not necessary to test the corner case in CI")
def test_patch_scheme(self, tiny_opt_model_path):
target_bits = 5
scheme = AutoScheme(avg_bits=target_bits, options=("MXFP4", "W8A16"))
- ar = AutoRound(model=tiny_opt_model_path, scheme=scheme, iters=0, nsamples=1, group_size=32)
+ ar = AutoRound(
+ model=tiny_opt_model_path, scheme=scheme, iters=0, disable_opt_rtn=True, nsamples=1, group_size=32
+ )
model, layer_config = ar.quantize()
for n, m in model.named_modules():
if hasattr(m, "group_size"):
@@ -185,12 +206,15 @@ class TestAutoScheme:
print(avg_bits)
assert target_bits - 0.1 < avg_bits <= target_bits + 1e-3
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
def test_layer_config(self):
target_bits = 3.0
model_name = get_model_path("facebook/opt-125m")
scheme = AutoScheme(avg_bits=3, options=("W2A16", "W4A16", "BF16"))
user_layer_config = {"model.decoder.layers.10.fc1": {"bits": 8, "group_size": 32, "sym": False}}
- ar = AutoRound(model=model_name, scheme=scheme, iters=0, nsamples=1, layer_config=user_layer_config)
+ ar = AutoRound(
+ model=model_name, scheme=scheme, iters=0, disable_opt_rtn=True, nsamples=1, layer_config=user_layer_config
+ )
model, layer_config = ar.quantize()
assert layer_config["model.decoder.layers.10.fc1"]["bits"] == 8
assert layer_config["model.decoder.layers.10.fc1"]["sym"] is False
@@ -206,7 +230,9 @@ class TestAutoScheme:
target_bits = 5.5
scheme = AutoScheme(avg_bits=target_bits, options=("mxfp4", "mxfp8"))
user_layer_config = {"model.decoder.layers.10.fc1": {"bits": 8, "group_size": 32, "sym": False}}
- ar = AutoRound(model=model_name, scheme=scheme, iters=0, nsamples=1, layer_config=user_layer_config)
+ ar = AutoRound(
+ model=model_name, scheme=scheme, iters=0, disable_opt_rtn=True, nsamples=1, layer_config=user_layer_config
+ )
model, layer_config = ar.quantize()
assert layer_config["model.decoder.layers.10.fc1"]["bits"] == 8
assert layer_config["model.decoder.layers.10.fc1"]["sym"] is False
@@ -219,37 +245,31 @@ class TestAutoScheme:
print(avg_bits)
assert target_bits - 0.1 < avg_bits <= target_bits + 1e-3
- def test_lm_head_and_mix_dtype(self):
- model_name = get_model_path("Qwen/Qwen3-8B")
- model = get_tiny_model(model_name)
- tokenizer = transformers.AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
- target_bits = 6
+ def test_lm_head_and_mix_dtype(self, tiny_untied_qwen_model_path):
+ target_bits = 5
scheme = AutoScheme(avg_bits=target_bits, options=("MXFP4", "MXFP8"))
- ar = AutoRound(model=model, tokenizer=tokenizer, scheme=scheme, iters=0, nsamples=1, quant_lm_head=True)
+ ar = AutoRound(
+ tiny_untied_qwen_model_path, scheme=scheme, iters=0, disable_opt_rtn=True, nsamples=1, quant_lm_head=True
+ )
model, layer_config = ar.quantize()
assert layer_config["lm_head"]["bits"] <= 8
avg_bits, _ = compute_avg_bits_for_model(model)
print(avg_bits)
# cause using tiny model
- assert 5.78 < avg_bits <= target_bits + 1e-3
+ assert 4.8 < avg_bits <= target_bits + 1e-3
+ @pytest.mark.skip_ci(reason="The evaluation is time-consuming")
def test_auto_scheme_export(self):
model_name = get_model_path("facebook/opt-125m")
scheme = AutoScheme(avg_bits=3, options=("W2A16", "W4A16", "W8A16", "BF16"))
ar = AutoRound(model=model_name, scheme=scheme)
- ar.quantize_and_save(self.save_dir)
+ ar.quantize()
evaluate_accuracy(self.save_dir, threshold=0.25)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- def test_auto_scheme_export_gguf(self, tiny_qwen_model_path):
- scheme = AutoScheme(avg_bits=3, options=("gguf:q2_k_s,gguf:q4_k_s"), nsamples=1, ignore_scale_zp_bits=True)
- ar = AutoRound(model=tiny_qwen_model_path, scheme=scheme, iters=0, nsamples=1)
- ar.quantize_and_save(self.save_dir)
+ @pytest.mark.skip_ci(reason="The evaluation is time-consuming")
def test_enable_torch_compile(self):
model_name = get_model_path("facebook/opt-125m")
scheme = AutoScheme(avg_bits=2, options=("W2A16"), ignore_scale_zp_bits=True)
ar = AutoRound(model=model_name, scheme=scheme, enable_torch_compile=True)
- ar.quantize_and_save(self.save_dir)
+ ar.quantize()
evaluate_accuracy(self.save_dir, threshold=0.10)
- shutil.rmtree(self.save_dir, ignore_errors=True)
diff --git a/test/test_cuda/backends/test_exllamav2_backend.py b/test/test_cuda/backends/test_exllamav2_backend.py
index 06a3cbec2..4ed812105 100644
--- a/test/test_cuda/backends/test_exllamav2_backend.py
+++ b/test/test_cuda/backends/test_exllamav2_backend.py
@@ -7,11 +7,16 @@ from transformers import AutoModelForCausalLM, AutoRoundConfig, AutoTokenizer
from auto_round import AutoRound
from ...envs import require_autogptq, require_gptqmodel, require_package_version_ut
-from ...helpers import evaluate_accuracy, generate_prompt, get_model_path, model_infer
+from ...helpers import eval_generated_prompt, evaluate_accuracy, generate_prompt, get_model_path, model_infer
class TestAutoRoundexllamaBackend:
- save_dir = "./saved"
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
@pytest.fixture(autouse=True, scope="class")
def setup_and_teardown_class(self):
@@ -23,9 +28,11 @@ class TestAutoRoundexllamaBackend:
# ===== TEARDOWN (teardown_class) =====
print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ # keep one CI test for exllamav2 backend, since it's the only backend supporting 4bits asym quantization.
+ # @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ # @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
@require_gptqmodel
def test_gptqmodel_exllmav2_4bits_asym(self, dataloader):
model_path = get_model_path("facebook/opt-125m")
@@ -54,8 +61,9 @@ class TestAutoRoundexllamaBackend:
model_infer(model, tokenizer)
evaluate_accuracy(model, tokenizer, threshold=0.35, batch_size=16)
torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
@require_autogptq
@require_package_version_ut("torch", "<2.6.0")
def test_gptq_exllamav2_4bits_sym(self, dataloader):
@@ -82,38 +90,35 @@ class TestAutoRoundexllamaBackend:
model_infer(model, tokenizer)
evaluate_accuracy(model, tokenizer, threshold=0.27, batch_size=16)
torch.cuda.empty_cache()
- shutil.rmtree(self.save_dir, ignore_errors=True)
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
@require_autogptq
@require_package_version_ut("torch", "<2.6.0")
- def test_gptq_exllamav2_4bits_sym_group_size(self):
+ @pytest.mark.parametrize("group_size", [-1, 32, 64, 128, 256, 1024])
+ def test_gptq_exllamav2_4bits_sym_group_size(self, group_size):
model_path = get_model_path("facebook/opt-125m")
- for group_size in [-1, 32, 64, 128, 256, 1024]: ## 384, 768 has accuracy issue
- print(f"!!!!!!!!!!!!!!!!!{group_size}!!!!!!!!!!!!!!!!!")
- bits, group_size, sym = 4, group_size, True
- autoround = AutoRound(
- model_path,
- bits=bits,
- iters=1,
- nsamples=1,
- group_size=group_size,
- sym=sym,
- )
- quantized_model_path = self.save_dir
- autoround.quantize_and_save(
- output_dir=quantized_model_path, format="auto_round"
- ) ##will convert to gptq model
-
- quantization_config = AutoRoundConfig(backend="gptq:exllamav2") ## or exllamav2
- model = AutoModelForCausalLM.from_pretrained(
- self.save_dir, torch_dtype=torch.float16, device_map="auto", quantization_config=quantization_config
- )
-
- tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- model_infer(model, tokenizer)
- evaluate_accuracy(model, tokenizer, threshold=0.15, batch_size=64)
- torch.cuda.empty_cache()
- shutil.rmtree(self.save_dir, ignore_errors=True)
+ print(f"!!!!!!!!!!!!!!!!!{group_size}!!!!!!!!!!!!!!!!!")
+ autoround = AutoRound(
+ model_path,
+ bits=4,
+ iters=0,
+ disable_opt_rtn=True,
+ group_size=group_size,
+ sym=True,
+ )
+ quantized_model_path = self.save_dir
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round") ##will convert to gptq model
+
+ quantization_config = AutoRoundConfig(backend="gptq:exllamav2") ## or exllamav2
+ model = AutoModelForCausalLM.from_pretrained(
+ self.save_dir, torch_dtype=torch.float16, device_map="auto", quantization_config=quantization_config
+ )
+
+ tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
+ model_infer(model, tokenizer)
+ evaluate_accuracy(model, tokenizer, threshold=0.15, batch_size=64)
+ torch.cuda.empty_cache()
@require_gptqmodel
def test_gptqmodel_awq_exllamav2_4bits_asym(self, dataloader):
@@ -121,7 +126,12 @@ class TestAutoRoundexllamaBackend:
model_path = get_model_path("facebook/opt-125m")
bits, group_size, sym = 4, 128, False
autoround = AutoRound(
- model_path, bits=bits, group_size=group_size, sym=sym, iters=1, seqlen=2, dataset=dataloader
+ model_path,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=0,
+ disable_opt_rtn=True,
)
quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round:auto_awq")
@@ -134,22 +144,25 @@ class TestAutoRoundexllamaBackend:
tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
# Inference generation check
- output = model_infer(model, tokenizer)
- assert isinstance(output, str) and len(output.strip()) > 0, "Model failed to generate non-empty output"
- generated = generate_prompt(model, tokenizer, "There is a girl who likes adventure,")
- assert len(generated) > len("There is a girl who likes adventure,"), "Generation did not produce new tokens"
+ eval_generated_prompt(model, tokenizer)
# Accuracy check
evaluate_accuracy(model, tokenizer, threshold=0.35, batch_size=16)
torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
@require_gptqmodel
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
def test_gptqmodel_awq_exllamav2_4bits_sym(self, dataloader):
"""Test AWQ quantization with gptqmodel:awq_exllamav2 backend (bfloat16 inference, symmetric)."""
model_path = get_model_path("facebook/opt-125m")
bits, group_size, sym = 4, 128, True
autoround = AutoRound(
- model_path, bits=bits, group_size=group_size, sym=sym, iters=1, seqlen=2, dataset=dataloader
+ model_path,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=0,
+ disable_opt_rtn=True,
)
quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round:auto_awq")
@@ -161,11 +174,7 @@ class TestAutoRoundexllamaBackend:
tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
# Inference generation check
- output = model_infer(model, tokenizer)
- assert isinstance(output, str) and len(output.strip()) > 0, "Model failed to generate non-empty output"
- generated = generate_prompt(model, tokenizer, "There is a girl who likes adventure,")
- assert len(generated) > len("There is a girl who likes adventure,"), "Generation did not produce new tokens"
+ eval_generated_prompt(model, tokenizer)
# Accuracy check
evaluate_accuracy(model, tokenizer, threshold=0.2, batch_size=16)
torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
diff --git a/test/test_cuda/backends/test_marlin_backend.py b/test/test_cuda/backends/test_marlin_backend.py
index 8cb24ee44..4d82e9058 100644
--- a/test/test_cuda/backends/test_marlin_backend.py
+++ b/test/test_cuda/backends/test_marlin_backend.py
@@ -7,13 +7,18 @@ from transformers import AutoModelForCausalLM, AutoRoundConfig, AutoTokenizer
from auto_round import AutoRound
from ...envs import require_gptqmodel
-from ...helpers import evaluate_accuracy, generate_prompt, get_model_path, model_infer
+from ...helpers import eval_generated_prompt, evaluate_accuracy, generate_prompt, get_model_path, model_infer
class TestAutoRoundMarlinBackend:
- save_dir = "./saved"
model_name = get_model_path("facebook/opt-125m")
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
@pytest.fixture(autouse=True, scope="class")
def setup_and_teardown_class(self):
# ===== SETUP (setup_class) =====
@@ -24,9 +29,40 @@ class TestAutoRoundMarlinBackend:
# ===== TEARDOWN (teardown_class) =====
print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ # Keep one CI test for marlin backend and skip others to save time.
+ # @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ # @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
+ def test_marlin_4bits_sym_with_zp_m_1(self, dataloader):
+ model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
+ bits, group_size, sym = 4, 128, True
+ autoround = AutoRound(
+ model,
+ tokenizer,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=1,
+ seqlen=2,
+ dataset=dataloader,
+ )
+ quantized_model_path = self.save_dir
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_gptq")
+
+ quantization_config = AutoRoundConfig(backend="marlin")
+ model = AutoModelForCausalLM.from_pretrained(
+ self.save_dir, torch_dtype=torch.float16, device_map="auto", quantization_config=quantization_config
+ )
+
+ tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
+ model_infer(model, tokenizer)
+ evaluate_accuracy(model, tokenizer, threshold=0.27, batch_size=16)
+ torch.cuda.empty_cache()
+
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
def test_marlin_group_size(self, dataloader):
for group_size in [-1, 64]:
print(f"{group_size}!!!!!!!!!!!!!!!!!")
@@ -82,43 +118,6 @@ class TestAutoRoundMarlinBackend:
model_infer(model, tokenizer)
evaluate_accuracy(model, tokenizer, threshold=0.14, batch_size=16)
- def test_marlin_4bits_sym_with_zp_m_1(self, dataloader):
- model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
- tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
- bits, group_size, sym = 4, 128, True
- autoround = AutoRound(
- model,
- tokenizer,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=1,
- seqlen=2,
- dataset=dataloader,
- )
- quantized_model_path = self.save_dir
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_gptq")
-
- quantization_config = AutoRoundConfig(backend="marlin")
- model = AutoModelForCausalLM.from_pretrained(
- self.save_dir, torch_dtype=torch.float16, device_map="auto", quantization_config=quantization_config
- )
-
- tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- model_infer(model, tokenizer)
- evaluate_accuracy(model, tokenizer, threshold=0.27, batch_size=16)
- torch.cuda.empty_cache()
-
- model = AutoModelForCausalLM.from_pretrained(
- self.save_dir, torch_dtype=torch.bfloat16, device_map="auto", quantization_config=quantization_config
- )
-
- tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- model_infer(model, tokenizer)
- evaluate_accuracy(model, tokenizer, threshold=0.27, batch_size=16)
- torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
-
# def test_marlin_4bits_sym(self):
# model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
# tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
@@ -167,12 +166,17 @@ class TestAutoRoundMarlinBackend:
# shutil.rmtree("./saved", ignore_errors=True)
@require_gptqmodel
- def test_gptqmodel_awq_marlin_4bits_sym(self, dataloader):
+ def test_gptqmodel_awq_marlin_4bits_sym(self):
"""Test AWQ quantization with gptqmodel:awq_marlin backend (sym-only, float16)."""
model_path = get_model_path("facebook/opt-125m")
bits, group_size, sym = 4, 128, True
autoround = AutoRound(
- model_path, bits=bits, group_size=group_size, sym=sym, iters=1, seqlen=2, dataset=dataloader
+ model_path,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=0,
+ disable_opt_rtn=True,
)
quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round:auto_awq")
@@ -184,50 +188,39 @@ class TestAutoRoundMarlinBackend:
tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
# Inference generation check
- output = model_infer(model, tokenizer)
- assert isinstance(output, str) and len(output.strip()) > 0, "Model failed to generate non-empty output"
- generated = generate_prompt(model, tokenizer, "There is a girl who likes adventure,")
- assert len(generated) > len("There is a girl who likes adventure,"), "Generation did not produce new tokens"
+ eval_generated_prompt(model, tokenizer)
# Accuracy check
evaluate_accuracy(model, tokenizer, threshold=0.2, batch_size=16)
torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
@require_gptqmodel
- def test_gptqmodel_awq_marlin_group_size(self, dataloader):
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
+ @pytest.mark.parametrize("group_size", [32, 64, 128])
+ def test_gptqmodel_awq_marlin_group_size(self, group_size):
"""Test AWQ marlin backend with different group sizes."""
- for group_size in [32, 64, 128]:
- print(f"!!!!!!!!!!!!!!!!!{group_size}!!!!!!!!!!!!!!!!!")
- model_path = get_model_path("facebook/opt-125m")
- bits, sym = 4, True
- autoround = AutoRound(
- model_path,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=1,
- seqlen=2,
- dataset=dataloader,
- )
- quantized_model_path = self.save_dir
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round:auto_awq")
+ print(f"!!!!!!!!!!!!!!!!!{group_size}!!!!!!!!!!!!!!!!!")
+ model_path = get_model_path("facebook/opt-125m")
+ bits, sym = 4, True
+ autoround = AutoRound(
+ model_path,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=0,
+ disable_opt_rtn=True,
+ )
+ quantized_model_path = self.save_dir
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round:auto_awq")
- quantization_config = AutoRoundConfig(backend="gptqmodel:awq_marlin")
- model = AutoModelForCausalLM.from_pretrained(
- self.save_dir, torch_dtype="auto", device_map="auto", quantization_config=quantization_config
- )
+ quantization_config = AutoRoundConfig(backend="gptqmodel:awq_marlin")
+ model = AutoModelForCausalLM.from_pretrained(
+ self.save_dir, torch_dtype="auto", device_map="auto", quantization_config=quantization_config
+ )
- tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- # Inference generation check
- output = model_infer(model, tokenizer)
- assert (
- isinstance(output, str) and len(output.strip()) > 0
- ), f"Model failed to generate non-empty output for group_size={group_size}"
- generated = generate_prompt(model, tokenizer, "There is a girl who likes adventure,")
- assert len(generated) > len(
- "There is a girl who likes adventure,"
- ), f"Generation did not produce new tokens for group_size={group_size}"
- # Accuracy check
- evaluate_accuracy(model, tokenizer, threshold=0.2, batch_size=16)
- torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
+ tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
+ # Inference generation check
+ eval_generated_prompt(model, tokenizer)
+ # Accuracy check
+ evaluate_accuracy(model, tokenizer, threshold=0.2, batch_size=16)
+ torch.cuda.empty_cache()
diff --git a/test/test_cuda/backends/test_torch_backend.py b/test/test_cuda/backends/test_torch_backend.py
index 649cbcd2c..dfd2c85eb 100644
--- a/test/test_cuda/backends/test_torch_backend.py
+++ b/test/test_cuda/backends/test_torch_backend.py
@@ -12,7 +12,11 @@ from ...helpers import evaluate_accuracy, generate_prompt, get_model_path, model
class TestAutoRoundTorchBackend:
- save_dir = "./saved"
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
@pytest.fixture(autouse=True, scope="class")
def setup_and_teardown_class(self):
@@ -24,9 +28,11 @@ class TestAutoRoundTorchBackend:
# ===== TEARDOWN (teardown_class) =====
print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ # Keep one CI test for torch backend and skip others to save time.
+ # @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ # @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
def test_torch_4bits_asym(self, dataloader):
model_path = get_model_path("facebook/opt-125m")
model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype="auto", trust_remote_code=True)
@@ -55,16 +61,8 @@ class TestAutoRoundTorchBackend:
evaluate_accuracy(model, tokenizer, threshold=0.35, batch_size=16)
torch.cuda.empty_cache()
- model = AutoModelForCausalLM.from_pretrained(
- self.save_dir, torch_dtype=torch.bfloat16, device_map="auto", quantization_config=quantization_config
- )
-
- tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- model_infer(model, tokenizer)
- evaluate_accuracy(model, tokenizer, threshold=0.35, batch_size=16)
- torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
-
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
def test_torch_4bits_sym(self, dataloader):
model_path = get_model_path("facebook/opt-125m")
model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype="auto", trust_remote_code=True)
@@ -87,20 +85,79 @@ class TestAutoRoundTorchBackend:
model = AutoModelForCausalLM.from_pretrained(
quantized_model_path, torch_dtype=torch.float16, device_map="auto", quantization_config=quantization_config
)
-
tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
model_infer(model, tokenizer)
evaluate_accuracy(model, tokenizer, threshold=0.28, batch_size=16)
torch.cuda.empty_cache()
+
+ def test_autoround_3bit_asym_torch_format(self, tiny_opt_model_path, dataloader):
+ bits, group_size, sym = 3, 128, False
+ autoround = AutoRound(
+ tiny_opt_model_path,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=2,
+ seqlen=2,
+ dataset=dataloader,
+ )
+ autoround.quantize()
+ quantized_model_path = self.save_dir
+
+ autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round:gptqmodel")
+
+ device = "auto" ##cpu, hpu, cuda
+ from transformers import AutoRoundConfig
+
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map=device)
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ text = "There is a girl who likes adventure,"
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
+ print(tokenizer.decode(model.generate(**inputs, max_new_tokens=10)[0]))
+
+ @pytest.mark.skip_ci(reason="Not necessary to test both symmetric and asymmetric for 3-bit quantization in CI")
+ def test_autoround_3bit_sym_torch_format(self, tiny_opt_model_path, dataloader):
+ bits, group_size, sym = 3, 128, True
+ autoround = AutoRound(
+ tiny_opt_model_path,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=2,
+ seqlen=2,
+ dataset=dataloader,
+ )
+ autoround.quantize()
+ quantized_model_path = self.save_dir
+
+ autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round")
+
+ device = "auto" ##cpu, hpu, cuda
+ from transformers import AutoRoundConfig
+
+ quantization_config = AutoRoundConfig(backend=device)
+ model = AutoModelForCausalLM.from_pretrained(
+ quantized_model_path, device_map=device, quantization_config=quantization_config
+ )
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ text = "There is a girl who likes adventure,"
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
+ print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
shutil.rmtree(self.save_dir, ignore_errors=True)
@require_gptqmodel
+ @pytest.mark.skip_ci(reason="Not necessary to test low priority backend in CI")
def test_gptqmodel_awq_torch_4bits_group_size_16(self, dataloader):
"""Test AWQ quantization with gptqmodel:awq_torch backend (group_size=16, float16)."""
model_path = get_model_path("facebook/opt-125m")
bits, group_size, sym = 4, 16, True
autoround = AutoRound(
- model_path, bits=bits, group_size=group_size, sym=sym, iters=1, seqlen=2, dataset=dataloader
+ model_path,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=0,
+ disable_opt_rtn=True,
)
quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round:auto_awq")
diff --git a/test/test_cuda/backends/test_triton_backend.py b/test/test_cuda/backends/test_triton_backend.py
index 5200494f5..6675d1620 100644
--- a/test/test_cuda/backends/test_triton_backend.py
+++ b/test/test_cuda/backends/test_triton_backend.py
@@ -7,37 +7,35 @@ from transformers import AutoModelForCausalLM, AutoRoundConfig, AutoTokenizer
from auto_round import AutoRound
from ...envs import require_greater_than_050
-from ...helpers import evaluate_accuracy, model_infer
+from ...helpers import evaluate_accuracy, get_model_path, model_infer
class TestAutoRoundTritonBackend:
@classmethod
def setup_class(self):
- self.model_name = "/models/opt-125m"
- self.save_folder = "./saved"
+ self.model_name = get_model_path("facebook/opt-125m")
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_folder = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_folder, ignore_errors=True)
@classmethod
def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ # Keep 2 bits symmetric test for triton backend since it's a special configuration and we want to make sure it's working well.
+ # @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ # @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
@require_greater_than_050
- def test_tritonv2_4bits_asym(self, dataloader):
+ def test_tritonv2_2bits_asym(self):
model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
- bits, group_size, sym = 4, 128, False
- autoround = AutoRound(
- model,
- tokenizer,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=1,
- seqlen=2,
- dataset=dataloader,
- )
+ bits, group_size, sym = 2, 32, False
+ autoround = AutoRound(model, tokenizer, bits=bits, group_size=group_size, sym=sym)
quantized_model_path = self.save_folder
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round:gptqmodel")
+ autoround.quantize_and_save(output_dir=quantized_model_path)
quantization_config = AutoRoundConfig(backend="tritonv2")
model = AutoModelForCausalLM.from_pretrained(
@@ -46,27 +44,28 @@ class TestAutoRoundTritonBackend:
tokenizer = AutoTokenizer.from_pretrained(self.save_folder)
model_infer(model, tokenizer)
- evaluate_accuracy(model, tokenizer, threshold=0.34, batch_size=16)
- torch.cuda.empty_cache()
-
- model = AutoModelForCausalLM.from_pretrained(
- self.save_folder, torch_dtype=torch.bfloat16, device_map="auto", quantization_config=quantization_config
- )
-
- tokenizer = AutoTokenizer.from_pretrained(self.save_folder)
- model_infer(model, tokenizer)
- evaluate_accuracy(model, tokenizer, threshold=0.34, batch_size=16)
+ evaluate_accuracy(model, tokenizer, threshold=0.19, batch_size=16)
torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
@require_greater_than_050
- def test_tritonv2_2bits_asym(self):
+ def test_tritonv2_4bits_asym(self, dataloader):
model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
- bits, group_size, sym = 2, 32, False
- autoround = AutoRound(model, tokenizer, bits=bits, group_size=group_size, sym=sym)
+ bits, group_size, sym = 4, 128, False
+ autoround = AutoRound(
+ model,
+ tokenizer,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=1,
+ seqlen=2,
+ dataset=dataloader,
+ )
quantized_model_path = self.save_folder
- autoround.quantize_and_save(output_dir=quantized_model_path)
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round:gptqmodel")
quantization_config = AutoRoundConfig(backend="tritonv2")
model = AutoModelForCausalLM.from_pretrained(
@@ -75,19 +74,11 @@ class TestAutoRoundTritonBackend:
tokenizer = AutoTokenizer.from_pretrained(self.save_folder)
model_infer(model, tokenizer)
- evaluate_accuracy(model, tokenizer, threshold=0.19, batch_size=16)
- torch.cuda.empty_cache()
-
- model = AutoModelForCausalLM.from_pretrained(
- self.save_folder, torch_dtype=torch.bfloat16, device_map="auto", quantization_config=quantization_config
- )
-
- tokenizer = AutoTokenizer.from_pretrained(self.save_folder)
- model_infer(model, tokenizer)
- evaluate_accuracy(model, tokenizer, threshold=0.19, batch_size=16)
+ evaluate_accuracy(model, tokenizer, threshold=0.34, batch_size=16)
torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
@require_greater_than_050
def test_tritonv2_4bits_sym(self, dataloader):
model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
@@ -125,8 +116,8 @@ class TestAutoRoundTritonBackend:
evaluate_accuracy(model, tokenizer, threshold=0.26, batch_size=16)
torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
-
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
@require_greater_than_050
def test_tritonv2_8bits_sym(self):
model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
@@ -154,8 +145,9 @@ class TestAutoRoundTritonBackend:
model_infer(model, tokenizer)
evaluate_accuracy(model, tokenizer, threshold=0.27, batch_size=16)
torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
@require_greater_than_050
def test_tritonv2_2bits_sym(self):
model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
@@ -189,4 +181,3 @@ class TestAutoRoundTritonBackend:
model_infer(model, tokenizer)
evaluate_accuracy(model, tokenizer, threshold=0.18, batch_size=16)
torch.cuda.empty_cache()
- shutil.rmtree("./saved", ignore_errors=True)
diff --git a/test/test_cuda/schemes/__init__.py b/test/test_cuda/calibration/__init__.py
similarity index 100%
rename from test/test_cuda/schemes/__init__.py
rename to test/test_cuda/calibration/__init__.py
diff --git a/test/test_cuda/utils/test_calib_dataset.py b/test/test_cuda/calibration/test_calib_dataset.py
similarity index 100%
rename from test/test_cuda/utils/test_calib_dataset.py
rename to test/test_cuda/calibration/test_calib_dataset.py
diff --git a/test/test_cuda/utils/test_customized_data.py b/test/test_cuda/calibration/test_customized_data.py
similarity index 71%
rename from test/test_cuda/utils/test_customized_data.py
rename to test/test_cuda/calibration/test_customized_data.py
index e9ce2207a..f65bc4d2b 100644
--- a/test/test_cuda/utils/test_customized_data.py
+++ b/test/test_cuda/calibration/test_customized_data.py
@@ -2,58 +2,63 @@ import copy
import re
import shutil
import sys
-import unittest
-sys.path.insert(0, "../..")
+import pytest
from transformers import AutoModelForCausalLM, AutoRoundConfig, AutoTokenizer
from auto_round import AutoRound
+from ...helpers import get_model_path
-class TestCustomizedData(unittest.TestCase):
- @classmethod
- def setUpClass(self):
- self.save_dir = "./saved"
- @classmethod
- def tearDownClass(self):
- shutil.rmtree("./saved", ignore_errors=True)
+class TestCustomizedData:
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
+ @pytest.fixture(autouse=True, scope="class")
+ def setup_and_teardown_class(self):
+ yield
shutil.rmtree("runs", ignore_errors=True)
- def test_mixed_attention_mask(self):
- model_name = "/models/Qwen3-0.6B"
+ def test_list_batch_encoding(self, tiny_qwen_model_path):
+ model_name = tiny_qwen_model_path
tokenizer = AutoTokenizer.from_pretrained(model_name)
+
texts = [
"There is a girl who likes adventure,",
"Tell me a story about a brave robot,",
"Explain why the sky is blue,",
]
-
inputs = tokenizer(texts, padding=True, truncation=True, max_length=9, return_tensors="pt")
- inputs = inputs["input_ids"]
- inputs = inputs.split(dim=0, split_size=1)
- ar = AutoRound(model_name, dataset=inputs, seqlen=9)
+ ar = AutoRound(model_name, dataset=[inputs], seqlen=9)
ar.quantize()
- def test_batch_encoding(self):
- model_name = "/models/Qwen3-0.6B"
- model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", torch_dtype="auto")
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ def test_mixed_attention_mask(self):
+ model_name = get_model_path("Qwen/Qwen3-0.6B")
tokenizer = AutoTokenizer.from_pretrained(model_name)
-
texts = [
"There is a girl who likes adventure,",
"Tell me a story about a brave robot,",
"Explain why the sky is blue,",
]
- inputs = tokenizer(texts, padding=True, truncation=True, max_length=9, return_tensors="pt").to(model.device)
+ inputs = tokenizer(texts, padding=True, truncation=True, max_length=9, return_tensors="pt")
+ inputs = inputs["input_ids"]
+ inputs = inputs.split(dim=0, split_size=1)
ar = AutoRound(model_name, dataset=inputs, seqlen=9)
ar.quantize()
- def test_list_batch_encoding(self):
- model_name = "/models/Qwen3-0.6B"
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ def test_batch_encoding(self):
+ model_name = get_model_path("Qwen/Qwen3-0.6B")
+ model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", torch_dtype="auto")
tokenizer = AutoTokenizer.from_pretrained(model_name)
texts = [
@@ -61,7 +66,8 @@ class TestCustomizedData(unittest.TestCase):
"Tell me a story about a brave robot,",
"Explain why the sky is blue,",
]
- inputs = tokenizer(texts, padding=True, truncation=True, max_length=9, return_tensors="pt")
- ar = AutoRound(model_name, dataset=[inputs], seqlen=9)
+ inputs = tokenizer(texts, padding=True, truncation=True, max_length=9, return_tensors="pt").to(model.device)
+
+ ar = AutoRound(model_name, dataset=inputs, seqlen=9)
ar.quantize()
diff --git a/test/test_cuda/core/test_main_func.py b/test/test_cuda/core/test_main_func.py
deleted file mode 100644
index 0e2d11b68..000000000
--- a/test/test_cuda/core/test_main_func.py
+++ /dev/null
@@ -1,177 +0,0 @@
-import copy
-import shutil
-
-import pytest
-import torch
-import transformers
-from lm_eval.utils import make_table # pylint: disable=E0401
-from transformers import AutoModelForCausalLM, AutoTokenizer
-from transformers.utils.versions import require_version
-
-from auto_round import AutoRound, AutoRoundAdam
-
-from ...envs import require_awq, require_gptqmodel, require_optimum
-from ...helpers import evaluate_accuracy, get_model_path
-
-
-class TestMainFunc:
- save_dir = "./saved"
-
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
- yield
-
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- @require_gptqmodel
- def test_backend(self):
- model_name = get_model_path("facebook/opt-125m")
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- autoround = AutoRound(model, tokenizer, bits=4, group_size=128)
- autoround.quantize()
-
- ##test auto_round format
- autoround.save_quantized(self.save_dir, format="auto_round", inplace=False)
- evaluate_accuracy(self.save_dir, threshold=0.35, batch_size="auto")
- shutil.rmtree("./saved", ignore_errors=True)
-
- ##test auto_gptq format
- autoround.save_quantized(self.save_dir, format="auto_gptq", inplace=False)
- evaluate_accuracy(self.save_dir, threshold=0.35, batch_size="auto")
- shutil.rmtree("./saved", ignore_errors=True)
-
- @require_gptqmodel
- def test_backend_awq(self):
- model_name = get_model_path("facebook/opt-125m")
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- autoround = AutoRound(model, tokenizer, bits=4, group_size=128)
- autoround.quantize()
-
- ##test auto_awq format
- autoround.save_quantized(self.save_dir, format="auto_awq", inplace=False)
- evaluate_accuracy(self.save_dir, threshold=0.35, batch_size="auto")
- shutil.rmtree("./saved", ignore_errors=True)
-
- @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available")
- @require_gptqmodel
- def test_ignore_layers(self):
- model_name = get_model_path("facebook/opt-125m")
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- from auto_round.compressors.utils import get_fp_layer_names
-
- layer_names = get_fp_layer_names(model, "model.decoder.layers.0,model.decoder.layers.1")
- layer_configs = {}
- for name in layer_names:
- layer_configs[name] = {"bits": 16}
- autoround = AutoRound(model, tokenizer, bits=4, group_size=128)
- autoround.quantize()
-
- ##test auto_round format
- autoround.save_quantized(self.save_dir, format="auto_round", inplace=False)
- evaluate_accuracy(self.save_dir, threshold=0.35, batch_size="auto")
- shutil.rmtree("./saved", ignore_errors=True)
-
- @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available")
- @require_gptqmodel
- def test_ignore_layers_awq(self):
- model_name = get_model_path("facebook/opt-125m")
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- from auto_round.compressors.utils import get_fp_layer_names
-
- layer_names = get_fp_layer_names(model, "model.decoder.layers.0,model.decoder.layers.1")
- layer_configs = {}
- for name in layer_names:
- layer_configs[name] = {"bits": 16}
- autoround = AutoRound(model, tokenizer, bits=4, group_size=128)
- autoround.quantize()
-
- ##test auto_awq format
- autoround.save_quantized(self.save_dir, format="auto_awq", inplace=False)
- evaluate_accuracy(self.save_dir, threshold=0.35, batch_size="auto")
- shutil.rmtree("./saved", ignore_errors=True)
-
- @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available")
- def test_undivided_group_size_tuning(self, tiny_opt_model_path):
- model = AutoModelForCausalLM.from_pretrained(tiny_opt_model_path, torch_dtype=torch.float16, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(tiny_opt_model_path)
-
- autoround = AutoRound(model, tokenizer, bits=4, group_size=127, nsamples=2, iters=2)
- autoround.quantize()
-
- @require_gptqmodel
- def test_adam(self):
- model_name = get_model_path("facebook/opt-125m")
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- autoround = AutoRoundAdam(model, tokenizer, bits=4, group_size=128)
- autoround.quantize()
-
- ##test auto_round format
- autoround.save_quantized(self.save_dir, format="auto_round", inplace=False)
- evaluate_accuracy(self.save_dir, threshold=0.34, batch_size="auto")
- shutil.rmtree("./saved", ignore_errors=True)
-
- def test_autoround_asym(self): ##need to install false
- try:
- from autoround_exllamav2_kernels import gemm_half_q_half, make_q_matrix
- except ImportError as e:
- print("skip autoround asym test, as autoround is not installed from source")
- return
- model_name = get_model_path("facebook/opt-125m")
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- autoround = AutoRound(model, tokenizer, bits=4, group_size=128, sym=False)
- autoround.quantize()
-
- ##test auto_round format
- autoround.save_quantized(self.save_dir, format="auto_round", inplace=False)
- evaluate_accuracy(self.save_dir, threshold=0.35, batch_size="auto")
- shutil.rmtree("./saved", ignore_errors=True)
-
- def test_attention_mask_lm_head(self, tiny_qwen_moe_model_path):
- from transformers import AutoTokenizer
-
- # model_name = "/models/Qwen3-8B"
- # model_name = "/models/Qwen3-0.6B"
- tokenizer = AutoTokenizer.from_pretrained(tiny_qwen_moe_model_path)
- text = ["haha", "hello world"]
- res = tokenizer(text, return_tensors="pt", max_length=8, padding="max_length", truncation=True)
- res.data.pop("attention_mask")
- data = [res.data]
-
- text = ["qudd", "hfd"]
- res = tokenizer(text, return_tensors="pt", max_length=8, padding="max_length", truncation=True)
- res.data.pop("attention_mask")
- data.append(res.data)
- from auto_round import AutoRound
-
- ar = AutoRound(tiny_qwen_moe_model_path, iters=1, dataset=data, seqlen=8, quant_lm_head=True)
- ar.quantize()
-
- def test_low_cpu_mem_usage(self, tiny_opt_model_path):
- bits, group_size = 4, 32
- model = AutoModelForCausalLM.from_pretrained(tiny_opt_model_path, torch_dtype="auto", trust_remote_code=True)
- tokenizer = AutoTokenizer.from_pretrained(tiny_opt_model_path, trust_remote_code=True)
- quantized_model_path = "./saved"
- autoround = AutoRound(
- model,
- tokenizer,
- bits=bits,
- group_size=group_size,
- iters=2,
- seqlen=10,
- low_cpu_mem_usage=True,
- )
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
- shutil.rmtree(quantized_model_path, ignore_errors=True)
diff --git a/test/test_cuda/export/test_auto_awq_format.py b/test/test_cuda/export/test_auto_awq_format.py
new file mode 100644
index 000000000..394b6ab9f
--- /dev/null
+++ b/test/test_cuda/export/test_auto_awq_format.py
@@ -0,0 +1,109 @@
+import copy
+import os
+import shutil
+
+import pytest
+import torch
+import transformers
+from packaging import version
+from transformers import AutoConfig, AutoModelForCausalLM, AutoRoundConfig, AutoTokenizer
+
+from auto_round import AutoRound
+
+from ...envs import require_gptqmodel
+from ...helpers import eval_generated_prompt, generate_prompt, get_model_path
+
+
+class TestAutoRound:
+
+ @pytest.fixture(autouse=True, scope="class")
+ def setup_and_teardown_class(self):
+ # ===== SETUP (setup_class) =====
+ print("[Setup] Running before any test in class")
+
+ # Yield to hand control to the test methods
+ yield
+
+ # ===== TEARDOWN (teardown_class) =====
+ print("[Teardown] Running after all tests in class")
+ shutil.rmtree("runs", ignore_errors=True)
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
+ @require_gptqmodel
+ def test_autoawq_format(self, tiny_opt_model_path):
+ bits, group_size, sym = 4, 128, False
+ autoround = AutoRound(
+ tiny_opt_model_path,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=0,
+ disable_opt_rtn=True,
+ )
+ autoround.quantize()
+ quantized_model_path = self.save_dir
+
+ autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_awq")
+
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
+ assert model is not None, "Loaded model should not be None."
+
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @require_gptqmodel
+ def test_autoawq_format_fp_qsave_layers(self):
+ layer_config = {
+ "model.decoder.layers.0.self_attn.k_proj": {"bits": 16},
+ }
+ bits, group_size, sym = 4, 128, False
+ autoround = AutoRound(
+ get_model_path("facebook/opt-125m"),
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=0,
+ disable_opt_rtn=True,
+ layer_config=layer_config,
+ )
+ quantized_model_path = os.path.join(self.save_dir, "test_export")
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_awq")
+
+ # test loading with AutoRoundConfig
+ model = AutoModelForCausalLM.from_pretrained(
+ quantized_model_path, device_map="auto", quantization_config=AutoRoundConfig()
+ )
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ eval_generated_prompt(model, tokenizer)
+
+ # test loading without quantization_config
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ eval_generated_prompt(model, tokenizer)
+
+ @require_gptqmodel
+ def test_fallback_regex_for_awq_format(self, tiny_opt_model_path, dataloader):
+ layer_config = {
+ "lm_head": {"bits": 16},
+ "fc1": {"bits": 16},
+ }
+ autoround = AutoRound(
+ model=tiny_opt_model_path,
+ scheme="W4A16",
+ iters=2,
+ seqlen=2,
+ dataset=dataloader,
+ layer_config=layer_config,
+ )
+ quantized_model_path = "self.save_dir"
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_awq")
+ quantization_config = AutoRoundConfig()
+ model = AutoModelForCausalLM.from_pretrained(
+ quantized_model_path, device_map="auto", quantization_config=quantization_config
+ )
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ generate_prompt(model, tokenizer)
+ shutil.rmtree(quantized_model_path, ignore_errors=True)
diff --git a/test/test_cuda/export/test_auto_gptq_format.py b/test/test_cuda/export/test_auto_gptq_format.py
new file mode 100644
index 000000000..2e98ad71b
--- /dev/null
+++ b/test/test_cuda/export/test_auto_gptq_format.py
@@ -0,0 +1,84 @@
+import copy
+import shutil
+
+import pytest
+import torch
+import transformers
+from packaging import version
+from transformers import AutoConfig, AutoModelForCausalLM, AutoRoundConfig, AutoTokenizer
+
+from auto_round import AutoRound
+
+from ...envs import require_optimum
+from ...helpers import eval_generated_prompt, get_model_path, get_tiny_model, transformers_version
+
+
+class TestAutoRound:
+
+ @pytest.fixture(autouse=True, scope="class")
+ def setup_and_teardown_class(self):
+ # ===== SETUP (setup_class) =====
+ print("[Setup] Running before any test in class")
+
+ # Yield to hand control to the test methods
+ yield
+
+ # ===== TEARDOWN (teardown_class) =====
+ print("[Teardown] Running after all tests in class")
+ shutil.rmtree("runs", ignore_errors=True)
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
+ @require_optimum
+ def test_autogptq_format(self, tiny_opt_model_path):
+ bits, group_size, sym = 4, 128, False
+ autoround = AutoRound(
+ tiny_opt_model_path,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=0,
+ disable_opt_rtn=True,
+ )
+ autoround.quantize()
+ quantized_model_path = self.save_dir
+
+ autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_gptq")
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto", trust_remote_code=True)
+ assert model is not None, "Loaded model should not be None."
+
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested") # skip this test in CI
+ def test_autogptq_format_qsave_ignore_layers(self):
+ model = AutoModelForCausalLM.from_pretrained(get_model_path("facebook/opt-125m"))
+
+ layer_config = {}
+ for n, m in model.named_modules():
+ if "q_proj" in n:
+ layer_config[n] = {"bits": 16}
+
+ bits, group_size, sym = 4, 128, False
+ autoround = AutoRound(
+ get_model_path("facebook/opt-125m"),
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=0,
+ disable_opt_rtn=True,
+ layer_config=layer_config,
+ )
+ quantized_model_path = self.save_dir
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_gptq")
+
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto", trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ eval_generated_prompt(model, tokenizer)
+
+ model = AutoModelForCausalLM.from_pretrained(
+ quantized_model_path, device_map="auto", trust_remote_code=True, quantization_config=AutoRoundConfig()
+ )
+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ eval_generated_prompt(model, tokenizer)
diff --git a/test/test_cuda/export/test_auto_round_format.py b/test/test_cuda/export/test_auto_round_format.py
index 155aca37c..02dd40b1c 100644
--- a/test/test_cuda/export/test_auto_round_format.py
+++ b/test/test_cuda/export/test_auto_round_format.py
@@ -15,11 +15,10 @@ from ...envs import (
require_greater_than_050,
require_ipex,
)
-from ...helpers import evaluate_accuracy, get_model_path, get_tiny_model, model_infer
+from ...helpers import eval_generated_prompt, evaluate_accuracy, get_model_path, is_cuda_support_fp8
class TestAutoRound:
- save_dir = "./saved"
@pytest.fixture(autouse=True, scope="class")
def setup_and_teardown_class(self):
@@ -31,38 +30,36 @@ class TestAutoRound:
# ===== TEARDOWN (teardown_class) =====
print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
@require_greater_than_050
- def test_autoround_asym(self, tiny_opt_model_path, dataloader):
- for bits in [2, 3, 4, 8]:
- # model_name = get_model_path("facebook/opt-125m")
- bits, group_size, sym = bits, 128, False
- autoround = AutoRound(
- tiny_opt_model_path,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=2,
- seqlen=2,
- dataset=dataloader,
- )
- quantized_model_path = self.save_dir
-
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
-
- model = AutoModelForCausalLM.from_pretrained(
- quantized_model_path, device_map="cuda:0", trust_remote_code=True
- )
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
- print(res)
- assert "!!!" not in res
- shutil.rmtree(self.save_dir, ignore_errors=True)
+ @pytest.mark.parametrize("bits", [2, 3, 4, 8])
+ @pytest.mark.parametrize("group_size", [32, 128])
+ @pytest.mark.parametrize("is_sym", [True, False])
+ def test_autoround_format(self, tiny_opt_model_path, bits, group_size, is_sym):
+ autoround = AutoRound(
+ tiny_opt_model_path,
+ bits=bits,
+ group_size=group_size,
+ sym=is_sym,
+ iters=0,
+ disable_opt_rtn=True,
+ )
+ quantized_model_path = self.save_dir
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
+
+ # Verify loading
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="cuda:0", trust_remote_code=True)
+ assert isinstance(model, torch.nn.Module), "Loaded model is not an instance of torch.nn.Module"
+
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
@require_autogptq
def test_mixed_precision(self):
model_name = get_model_path("facebook/opt-125m")
@@ -78,16 +75,10 @@ class TestAutoRound:
autoround = AutoRound(model_name, bits=bits, group_size=group_size, sym=sym, layer_config=layer_config)
quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
- quantization_config = AutoRoundConfig(backend="auto")
- model = AutoModelForCausalLM.from_pretrained(
- self.save_dir, torch_dtype=torch.float16, device_map="auto", quantization_config=quantization_config
- )
-
- tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- model_infer(model, tokenizer)
- evaluate_accuracy(model, tokenizer, threshold=0.32, batch_size=16)
- shutil.rmtree(self.save_dir, ignore_errors=True)
+ eval_generated_prompt(quantized_model_path)
+ evaluate_accuracy(quantized_model_path, threshold=0.32, batch_size=16)
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
@require_gptqmodel
def test_awq_backend(self):
model_name = get_model_path("facebook/opt-125m")
@@ -109,7 +100,7 @@ class TestAutoRound:
)
tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- model_infer(model, tokenizer)
+ eval_generated_prompt(model, tokenizer)
evaluate_accuracy(model, tokenizer, threshold=0.18, batch_size=16)
torch.cuda.empty_cache()
@@ -118,22 +109,21 @@ class TestAutoRound:
)
tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- model_infer(model, tokenizer)
- shutil.rmtree(self.save_dir, ignore_errors=True)
+ eval_generated_prompt(model, tokenizer)
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
@require_greater_than_050
def test_tritonv2_bf16(self):
model_name = get_model_path("OPEA/Meta-Llama-3.1-8B-Instruct-int4-sym-inc")
quantization_config = AutoRoundConfig(backend="tritonv2")
- model = get_tiny_model(
+ model = AutoModelForCausalLM.from_pretrained(
model_name, torch_dtype=torch.bfloat16, device_map="auto", quantization_config=quantization_config
)
-
tokenizer = AutoTokenizer.from_pretrained(model_name)
- model_infer(model, tokenizer)
-
+ eval_generated_prompt(model, tokenizer)
torch.cuda.empty_cache()
+ @pytest.mark.skip_ci(reason="IPEX is deprecated.")
@require_ipex
def test_autoround_gptq_sym_format(self, tiny_opt_model_path, dataloader):
bits, group_size, sym = 4, 128, True
@@ -146,7 +136,7 @@ class TestAutoRound:
seqlen=2,
dataset=dataloader,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path)
@@ -182,8 +172,7 @@ class TestAutoRound:
print(res)
assert "!!!" not in res
- shutil.rmtree("./saved", ignore_errors=True)
-
+ @pytest.mark.skip_ci(reason="IPEX is deprecated.")
@require_awq
@require_ipex
def test_autoround_awq_sym_format(self, tiny_opt_model_path, dataloader):
@@ -197,7 +186,7 @@ class TestAutoRound:
seqlen=2,
dataset=dataloader,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round:auto_awq")
@@ -219,46 +208,23 @@ class TestAutoRound:
print(res)
assert "!!!" not in res
- shutil.rmtree("./saved", ignore_errors=True)
+ def test_fp8_block_fp8_format(self):
+ model_name = "Qwen/Qwen3-0.6B"
- @require_greater_than_050
- def test_autoround_sym(self, tiny_opt_model_path, dataloader):
- for bits in [2, 3, 4, 8]:
- bits, group_size, sym = bits, 128, True
- autoround = AutoRound(
- tiny_opt_model_path,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=2,
- seqlen=2,
- dataset=dataloader,
- )
- quantized_model_path = "./saved"
-
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
-
- model = AutoModelForCausalLM.from_pretrained(
- quantized_model_path, device_map="auto", trust_remote_code=True
- )
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
- print(res)
- assert "!!!" not in res
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- @require_greater_than_050
- def test_load_gptq_model_3bits(self):
- model_name = get_model_path("LucasSantiago257/gemma-2b-2bits-gptq")
- quantization_config = AutoRoundConfig()
- model = AutoModelForCausalLM.from_pretrained(
+ scheme = "FP8_BLOCK"
+ autoround = AutoRound(
model_name,
- torch_dtype="auto",
- trust_remote_code=True,
- device_map="auto",
- quantization_config=quantization_config,
+ scheme=scheme,
+ iters=2,
+ seqlen=2,
)
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
- model_infer(model, tokenizer)
+ quantized_model_path = self.save_dir
+ compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="fp8")
+ tmp_layer = compressed_model.model.layers[1].self_attn.q_proj
+ assert hasattr(tmp_layer, "weight_scale_inv")
+ assert tmp_layer.weight.dtype is torch.float8_e4m3fn
+ assert list(tmp_layer.weight_scale_inv.shape) == [16, 8]
+ assert compressed_model.config.quantization_config["quant_method"] == "fp8"
+ assert compressed_model.config.quantization_config["weight_block_size"] == (128, 128)
+ if is_cuda_support_fp8():
+ eval_generated_prompt(quantized_model_path, device="cuda")
diff --git a/test/test_cuda/export/test_export.py b/test/test_cuda/export/test_export.py
deleted file mode 100644
index b3810e152..000000000
--- a/test/test_cuda/export/test_export.py
+++ /dev/null
@@ -1,441 +0,0 @@
-import copy
-import shutil
-
-import pytest
-import torch
-import transformers
-from packaging import version
-from transformers import AutoConfig, AutoModelForCausalLM, AutoRoundConfig, AutoTokenizer
-
-from auto_round import AutoRound
-
-from ...envs import require_gptqmodel, require_optimum
-from ...helpers import get_model_path, get_tiny_model, transformers_version
-
-
-class TestAutoRound:
- save_dir = "./saved"
-
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
- yield
-
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- @require_optimum
- def test_autogptq_format(self, dataloader):
- model_path = get_model_path("facebook/opt-125m")
- bits, group_size, sym = 4, 128, False
- autoround = AutoRound(
- model_path,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=2,
- seqlen=2,
- dataset=dataloader,
- )
- autoround.quantize()
- quantized_model_path = "./saved"
-
- autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_gptq")
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto", trust_remote_code=True)
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
- assert (
- res == "</s>There is a girl who likes adventure, she is a good friend of mine, she is a good friend of"
- " mine, she is a good friend of mine, she is a good friend of mine, she is a good friend of mine, "
- "she is a good friend of mine, she is"
- )
- shutil.rmtree("./saved", ignore_errors=True)
-
- @require_optimum
- def test_autogptq_format_ignore_layers(self, tiny_opt_model_path, dataloader):
- layer_config = {}
- model = AutoModelForCausalLM.from_pretrained(tiny_opt_model_path)
- tokenizer = AutoTokenizer.from_pretrained(tiny_opt_model_path)
- for n, m in model.named_modules():
- if "q_proj" in n:
- layer_config[n] = {"bits": 16}
-
- bits, group_size, sym = 4, 128, False
- autoround = AutoRound(
- model,
- tokenizer,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=1,
- seqlen=2,
- dataset=dataloader,
- layer_config=layer_config,
- )
- autoround.quantize()
- quantized_model_path = "./saved"
- autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_gptq")
-
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto", trust_remote_code=True)
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
- # Affected greatly by the transformers version
- # assert res == (
- # "</s>There is a girl who likes adventure, there there there there there there there there there there "
- # "there there there there there there there there there there there there there there there there there "
- # "there there there there there there there there there there there there there there there there there "
- # "there there there there there there")
- shutil.rmtree("./saved", ignore_errors=True)
-
- def test_autogptq_format_qsave_ignore_layers(self, dataloader):
- model_path = get_model_path("facebook/opt-125m")
- model = AutoModelForCausalLM.from_pretrained(model_path)
-
- layer_config = {}
- for n, m in model.named_modules():
- if "q_proj" in n:
- layer_config[n] = {"bits": 16}
-
- bits, group_size, sym = 4, 128, False
- autoround = AutoRound(
- model_path,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=1,
- seqlen=2,
- dataset=dataloader,
- layer_config=layer_config,
- )
- quantized_model_path = "./saved"
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_gptq")
-
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto", trust_remote_code=True)
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
- print(res)
- from transformers import AutoRoundConfig
-
- model = AutoModelForCausalLM.from_pretrained(
- quantized_model_path, device_map="auto", trust_remote_code=True, quantization_config=AutoRoundConfig()
- )
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- g_tokens = model.generate(**inputs, max_new_tokens=50)[0]
- res = tokenizer.decode(g_tokens)
- print(res)
- ##print(res)
- shutil.rmtree("./saved", ignore_errors=True)
-
- def test_autoround_format(self, tiny_opt_model_path, dataloader):
- bits, group_size, sym = 4, 128, True
- autoround = AutoRound(
- tiny_opt_model_path,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=1,
- seqlen=2,
- dataset=dataloader,
- )
- autoround.quantize()
- quantized_model_path = "./saved"
-
- autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round")
-
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
- print(res)
- # Affected greatly by the transformers version
- # assert res == ("</s>There is a girl who likes adventure, she is a great artist, she is a great artist,"
- # " she is a great artist, she is a great artist, she is a great artist, "
- # "she is a great artist, she is a great artist, she is a great artist, she is")
- shutil.rmtree("./saved", ignore_errors=True)
-
- @require_gptqmodel
- def test_autoawq_format(self, dataloader):
- model_path = get_model_path("facebook/opt-125m")
- bits, group_size, sym = 4, 128, False
- autoround = AutoRound(
- model_path,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=1,
- seqlen=2,
- dataset=dataloader,
- )
- autoround.quantize()
- quantized_model_path = "./saved"
-
- autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_awq")
-
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
- assert res == (
- "</s>There is a girl who likes adventure, but she's not a very good one.\nI don't"
- " know why you're getting downvoted. I think you're just being a dick.\nI'm not a dick, "
- "I just think it's funny that people are downvoting"
- )
- shutil.rmtree("./saved", ignore_errors=True)
-
- def test_autoawq_qwen3_vl_vllm_infer(self, dataloader):
- pytest.importorskip("vllm")
- from vllm import LLM, SamplingParams
- from vllm.platforms import current_platform
-
- if not current_platform.is_cuda():
- pytest.skip("only supports CUDA backend for this test")
-
- model_path = get_model_path("Qwen/Qwen3-VL-2B-Instruct")
- autoround = AutoRound(
- model=model_path,
- scheme="W4A16",
- iters=0,
- seqlen=2,
- batch_size=1,
- dataset=dataloader,
- )
- quantized_model_path = "./saved"
- autoround.quantize_and_save(output_dir=quantized_model_path, inplace=False, format="auto_awq")
-
- # Check items of modules_to_not_convert in quantization config
- import json
-
- quantization_config_path = f"{quantized_model_path}/quantization_config.json"
- with open(quantization_config_path, "r") as f:
- quantization_config = json.load(f)
- modules_to_not_convert = quantization_config.get("modules_to_not_convert", [])
- assert (
- "model.visual.merger.linear_fc2" in modules_to_not_convert
- ), f"'model.visual.merger.linear_fc2' should be in modules_to_not_convert. Got: {modules_to_not_convert}"
- assert (
- "model.visual.blocks" in modules_to_not_convert
- ), f"'model.visual.blocks' should be in modules_to_not_convert. Got: {modules_to_not_convert}"
-
- sampling_params = SamplingParams(temperature=0.8, top_p=0.95, max_tokens=32)
- llm = LLM(
- model=quantized_model_path,
- quantization="awq",
- trust_remote_code=True,
- tensor_parallel_size=1,
- allow_deprecated_quantization=True,
- dtype="half",
- )
- outputs = llm.generate(["Tell me a short joke."], sampling_params)
- generated_text = outputs[0].outputs[0].text
- print(generated_text)
- assert "!!!" not in generated_text
- shutil.rmtree("./saved", ignore_errors=True)
-
- @require_gptqmodel
- def test_autoawq_format_fp_qsave_layers(self, dataloader):
- model_path = get_model_path("facebook/opt-125m")
- layer_config = {
- "model.decoder.layers.0.self_attn.k_proj": {"bits": 16},
- "model.decoder.layers.9.self_attn.v_proj": {"bits": 16},
- }
- bits, group_size, sym = 4, 128, False
- autoround = AutoRound(
- model_path,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=1,
- seqlen=2,
- dataset=dataloader,
- layer_config=layer_config,
- )
- quantized_model_path = "./saved/test_export"
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_awq")
- from transformers import AutoRoundConfig
-
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
- print(res)
-
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
- print(res)
-
- shutil.rmtree("./saved", ignore_errors=True)
-
- def test_autoround_3bit_asym_torch_format(self, tiny_opt_model_path, dataloader):
- bits, group_size, sym = 3, 128, False
- autoround = AutoRound(
- tiny_opt_model_path,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=2,
- seqlen=2,
- dataset=dataloader,
- )
- autoround.quantize()
- quantized_model_path = "./saved"
-
- autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round:gptqmodel")
-
- device = "auto" ##cpu, hpu, cuda
- from transformers import AutoRoundConfig
-
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map=device)
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree("./saved", ignore_errors=True)
-
- def test_autoround_3bit_sym_torch_format(self, tiny_opt_model_path, dataloader):
- bits, group_size, sym = 3, 128, True
- autoround = AutoRound(
- tiny_opt_model_path,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=2,
- seqlen=2,
- dataset=dataloader,
- )
- autoround.quantize()
- quantized_model_path = "./saved"
-
- autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round")
-
- device = "auto" ##cpu, hpu, cuda
- from transformers import AutoRoundConfig
-
- quantization_config = AutoRoundConfig(backend=device)
- model = AutoModelForCausalLM.from_pretrained(
- quantized_model_path, device_map=device, quantization_config=quantization_config
- )
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree("./saved", ignore_errors=True)
-
- @pytest.mark.skipif(
- transformers_version >= version.parse("5.0"),
- reason="PhiConfig missing pad_token_id, https://github.com/huggingface/transformers/pull/43453",
- )
- def test_awq_lmhead_export(self, dataloader):
- bits, sym, group_size = 4, False, 128
- model_name = get_model_path("microsoft/phi-2")
- tiny_model = get_tiny_model(model_name)
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- layer_config = {
- "lm_head": {"bits": 4}, # set lm_head quant
- }
- autoround = AutoRound(
- model=tiny_model,
- tokenizer=tokenizer,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=2,
- seqlen=2,
- layer_config=layer_config,
- dataset=dataloader,
- )
- quantized_model_path = "./saved"
- compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_awq")
- lm_head = compressed_model.lm_head
- from auto_round.export.export_to_awq.utils import WQLinear_GEMM
-
- assert isinstance(lm_head, WQLinear_GEMM), "Illegal AWQ quantization for lm_head layer"
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- @pytest.mark.skipif(
- transformers_version >= version.parse("5.0"),
- reason="PhiConfig missing pad_token_id, https://github.com/huggingface/transformers/pull/43453",
- )
- def test_gptq_lmhead_export(self, dataloader):
- bits, sym, group_size = 4, True, 128
- model_name = get_model_path("microsoft/phi-2")
- tiny_model = get_tiny_model(model_name)
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- layer_config = {
- "lm_head": {"bits": 4}, # set lm_head quant
- }
- autoround = AutoRound(
- model=tiny_model,
- tokenizer=tokenizer,
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=2,
- seqlen=2,
- layer_config=layer_config,
- dataset=dataloader,
- )
- quantized_model_path = "./saved"
- compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_gptq")
- lm_head = compressed_model.lm_head
- assert hasattr(lm_head, "bits") and lm_head.bits == 4, "Illegal GPTQ quantization for lm_head layer"
- quantization_config = AutoRoundConfig()
- model = AutoModelForCausalLM.from_pretrained(
- quantized_model_path, device_map="auto", quantization_config=quantization_config
- )
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=5)[0])
- print(res)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- def test_autogtq_qwen3_vl_vllm_infer(self, dataloader):
- pytest.importorskip("vllm")
- from vllm import LLM, SamplingParams
- from vllm.platforms import current_platform
-
- if not current_platform.is_cuda():
- pytest.skip("only supports CUDA backend for this test")
-
- model_path = get_model_path("Qwen/Qwen3-VL-2B-Instruct")
- autoround = AutoRound(
- model=model_path,
- scheme="W4A16",
- iters=0,
- seqlen=2,
- batch_size=1,
- dataset=dataloader,
- )
- quantized_model_path = "./saved"
- autoround.quantize_and_save(output_dir=quantized_model_path, inplace=False, format="auto_gptq")
- sampling_params = SamplingParams(temperature=0.8, top_p=0.95, max_tokens=20)
- llm = LLM(
- model=quantized_model_path,
- trust_remote_code=True,
- tensor_parallel_size=1,
- allow_deprecated_quantization=True,
- )
- outputs = llm.generate(["Tell me a short joke."], sampling_params)
- generated_text = outputs[0].outputs[0].text
- print(generated_text)
- assert "!!!" not in generated_text
- shutil.rmtree("./saved", ignore_errors=True)
diff --git a/test/test_cuda/export/test_fp8_format.py b/test/test_cuda/export/test_fp8_format.py
new file mode 100644
index 000000000..b612cf27d
--- /dev/null
+++ b/test/test_cuda/export/test_fp8_format.py
@@ -0,0 +1,45 @@
+import shutil
+
+import pytest
+import torch
+
+from auto_round import AutoRound
+
+from ...helpers import eval_generated_prompt, get_model_path, is_cuda_support_fp8
+
+
+class TestAutoRoundBlockFP:
+ @classmethod
+ def setup_class(self):
+ self.model_name = get_model_path("Qwen/Qwen3-0.6B")
+
+ @classmethod
+ def teardown_class(self):
+ shutil.rmtree("runs", ignore_errors=True)
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
+ def test_fp8_block_fp8_format(self):
+ model_name = self.model_name
+
+ scheme = "FP8_BLOCK"
+ autoround = AutoRound(
+ model_name,
+ scheme=scheme,
+ iters=2,
+ seqlen=2,
+ )
+ quantized_model_path = self.save_dir
+ compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="fp8")
+ tmp_layer = compressed_model.model.layers[1].self_attn.q_proj
+ assert hasattr(tmp_layer, "weight_scale_inv")
+ assert tmp_layer.weight.dtype is torch.float8_e4m3fn
+ assert list(tmp_layer.weight_scale_inv.shape) == [16, 8]
+ assert compressed_model.config.quantization_config["quant_method"] == "fp8"
+ assert compressed_model.config.quantization_config["weight_block_size"] == (128, 128)
+ if is_cuda_support_fp8():
+ eval_generated_prompt(quantized_model_path, device="cuda")
diff --git a/test/test_cuda/export/test_gguf.py b/test/test_cuda/export/test_gguf_format.py
similarity index 54%
rename from test/test_cuda/export/test_gguf.py
rename to test/test_cuda/export/test_gguf_format.py
index 824bbbeb9..a89214616 100644
--- a/test/test_cuda/export/test_gguf.py
+++ b/test/test_cuda/export/test_gguf_format.py
@@ -11,14 +11,13 @@ from transformers import AutoModelForCausalLM, AutoTokenizer
from auto_round import AutoRound
from ...envs import require_gguf
-from ...helpers import evaluate_accuracy, get_model_path, get_tiny_model, save_tiny_model, transformers_version
+from ...helpers import eval_generated_prompt, evaluate_accuracy, generate_prompt, get_model_path, save_tiny_model
AUTO_ROUND_PATH = __file__.split("/")
AUTO_ROUND_PATH = "/".join(AUTO_ROUND_PATH[: AUTO_ROUND_PATH.index("test")])
class TestAutoRound:
- save_dir = "./saved"
@pytest.fixture(autouse=True, scope="class")
def setup_and_teardown_class(self):
@@ -30,9 +29,14 @@ class TestAutoRound:
# ===== TEARDOWN (teardown_class) =====
print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
@require_gguf
def test_gguf_format(self, tiny_qwen_model_path, dataloader):
bits, group_size, sym = 4, 32, False
@@ -47,42 +51,37 @@ class TestAutoRound:
dataset=dataloader,
)
autoround.quantize()
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.save_quantized(output_dir=quantized_model_path, format="gguf:q4_1")
- from llama_cpp import Llama
+ @require_gguf
+ def test_q4_0_accuracy(self):
+ model_name = get_model_path("Qwen/Qwen2.5-0.5B-Instruct")
+ bits, group_size, sym = 4, 32, True
+ autoround = AutoRound(
+ model_name, bits=bits, group_size=group_size, sym=sym, iters=0, data_type="int", disable_opt_rtn=True
+ )
+ autoround.quantize()
+ quantized_model_path = self.save_dir
- gguf_file = os.listdir("saved")[0]
- llm = Llama(f"saved/{gguf_file}", n_gpu_layers=-1)
- output = llm("There is a girl who likes adventure,", max_tokens=32)
- print(output)
- shutil.rmtree("./saved", ignore_errors=True)
+ autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="gguf:q4_0")
- save_dir = os.path.join(os.path.dirname(__file__), "saved")
- res = os.system(
- f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {sys.executable} -m auto_round --model {tiny_qwen_model_path} --iter 2 "
- f"--output_dir {save_dir} --nsample 2 --format gguf:q4_0 --device cuda"
- )
- print(save_dir)
- assert not (res > 0 or res == -1), "qwen2 tuning fail"
+ gguf_file = os.listdir(quantized_model_path)[0]
- from llama_cpp import Llama
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, gguf_file=gguf_file, device_map="auto")
+ eval_generated_prompt(model, autoround.tokenizer)
- gguf_file = os.listdir(f"{save_dir}/tiny_qwen_model_path-gguf")[0]
- llm = Llama(f"{save_dir}/tiny_qwen_model_path-gguf/{gguf_file}", n_gpu_layers=-1)
- output = llm("There is a girl who likes adventure,", max_tokens=32)
- print(output)
- shutil.rmtree(save_dir, ignore_errors=True)
+ evaluate_accuracy(model, autoround.tokenizer, threshold=0.54, batch_size=16, task="piqa")
+ @pytest.mark.skip_ci(reason="Not necessary to test all options in CI")
@require_gguf
def test_q2_k_export(self, dataloader):
bits, group_size, sym = 2, 16, False
- model_path = get_model_path("Qwen/Qwen2.5-1.5B-Instruct")
- model = get_tiny_model(model_path)
- tokenizer = AutoTokenizer.from_pretrained(model_path)
+ model_path = get_model_path("Qwen/Qwen2.5-0.5B-Instruct")
+ tiny_model_path = "./tmp/tmp_tiny_qwen_model_path"
+ save_tiny_model(model_path, tiny_model_path, num_layers=2)
autoround = AutoRound(
- model,
- tokenizer,
+ model_path,
bits=bits,
group_size=group_size,
sym=sym,
@@ -92,38 +91,19 @@ class TestAutoRound:
data_type="int_asym_dq",
)
autoround.quantize()
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="gguf:q2_k_s")
gguf_file = os.listdir(quantized_model_path)[0]
model = AutoModelForCausalLM.from_pretrained(quantized_model_path, gguf_file=gguf_file, device_map="auto")
- text = "There is a girl who likes adventure,"
- inputs = autoround.tokenizer(text, return_tensors="pt").to(model.device)
- result = autoround.tokenizer.decode(model.generate(**inputs, max_new_tokens=10)[0])
+ result = generate_prompt(model, autoround.tokenizer)
print(result)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- @require_gguf
- def test_q4_0(self):
- model_name = get_model_path("Qwen/Qwen2.5-0.5B-Instruct")
- bits, group_size, sym = 4, 32, True
- autoround = AutoRound(model_name, bits=bits, group_size=group_size, sym=sym, iters=1, data_type="int")
- autoround.quantize()
- quantized_model_path = "./saved"
-
- autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="gguf:q4_0")
- gguf_file = os.listdir(quantized_model_path)[0]
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, gguf_file=gguf_file, device_map="auto")
- text = "There is a girl who likes adventure,"
- inputs = autoround.tokenizer(text, return_tensors="pt").to(model.device)
- print(autoround.tokenizer.decode(model.generate(**inputs, max_new_tokens=10)[0]))
-
- evaluate_accuracy(model, autoround.tokenizer, threshold=0.54, batch_size=16, task="piqa")
- shutil.rmtree(quantized_model_path, ignore_errors=True)
+ shutil.rmtree(tiny_model_path, ignore_errors=True)
+ @pytest.mark.skip_ci(reason="Not necessary to test all options in CI")
@require_gguf
def test_all_format(self):
- for model_name in ["qwen/Qwen3-8B", "meta-llama/Llama-3.2-3B"]:
+ for model_name in ["Qwen/Qwen3-8B", "meta-llama/Llama-3.2-3B"]:
for gguf_format in ["gguf:q5_0", "gguf:q5_1", "gguf:q3_k_m", "gguf:q5_k_m", "gguf:q6_k", "gguf:q8_0"]:
model_path = get_model_path(model_name)
tiny_model_path = "tmp_tiny_model"
@@ -135,8 +115,8 @@ class TestAutoRound:
ar.quantize_and_save(output_dir=self.save_dir, format=gguf_format)
shutil.rmtree(tiny_model_path, ignore_errors=True)
- shutil.rmtree(self.save_dir, ignore_errors=True)
+ @pytest.mark.skip_ci(reason="Not necessary to test special models in CI")
@require_gguf
def test_special_model(self):
from ...helpers import save_tiny_model
@@ -151,20 +131,25 @@ class TestAutoRound:
nsamples=8,
disable_opt_rtn=True,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="gguf:q4_0")
file_name = os.listdir(quantized_model_path)[0]
file_size = os.path.getsize(os.path.join(quantized_model_path, file_name)) / 1024**2
assert abs(file_size - 307) < 5.0
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree(tiny_model_path, ignore_errors=True)
@require_gguf
def test_vlm_gguf(self):
+ from huggingface_hub import hf_hub_download
+
from ...helpers import save_tiny_model
- model_name = "/models/gemma-3-4b-it"
- tiny_model_path = save_tiny_model(model_name, "tiny_model_path", num_layers=3, is_mllm=True)
+ model_name = "google/gemma-3-4b-it"
+ tiny_model_path = save_tiny_model(model_name, "tiny_model_path", num_layers=3, is_mllm=True, use_fast=False)
+ # Needs tokenizer.model for gguf
+ # New transformers won't download it even with use_fast=False
+ file_path = hf_hub_download(repo_id=model_name, filename="tokenizer.model", local_dir=tiny_model_path)
+
from auto_round import AutoRound
autoround = AutoRound(
@@ -175,16 +160,66 @@ class TestAutoRound:
disable_opt_rtn=True,
quant_nontext_module=True,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="gguf:q4_k_m")
- assert "mmproj-model.gguf" in os.listdir("./saved")
- for file in os.listdir("./saved"):
- print(f"{file}: {os.path.getsize(os.path.join('./saved', file)) / 1024**2} MB")
- file_size = os.path.getsize(os.path.join("./saved", file)) / 1024**2
+ assert "mmproj-model.gguf" in os.listdir(self.save_dir)
+ for file in os.listdir(self.save_dir):
+ print(f"{file}: {os.path.getsize(os.path.join(self.save_dir, file)) / 1024**2} MB")
+ file_size = os.path.getsize(os.path.join(self.save_dir, file)) / 1024**2
if "mmproj-model.gguf" in file:
assert abs(file_size - 75) < 5.0
else:
assert abs(file_size - 690) < 5.0
- shutil.rmtree(quantized_model_path, ignore_errors=True)
shutil.rmtree(tiny_model_path, ignore_errors=True)
+
+ @pytest.mark.skip_ci(reason="Not necessary to test all options in CI")
+ def test_q2k_mixed(self):
+ model_path = get_model_path("miromind-ai/MiroThinker-v1.5-30B")
+ saved_tiny_model_path = save_tiny_model(
+ model_path,
+ "./tmp/tiny_qwen_model_path",
+ num_layers=3,
+ is_mllm=False,
+ )
+ autoround = AutoRound(
+ saved_tiny_model_path,
+ iters=0,
+ nsamples=1,
+ seqlen=16,
+ disable_opt_rtn=True,
+ )
+ quantized_model_path = self.save_dir
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="gguf:q2_k_mixed")
+ gguf_file = os.listdir(quantized_model_path)[0]
+ file_size = os.path.getsize(os.path.join(quantized_model_path, gguf_file)) / 1024**2
+ assert abs(file_size - 1236) < 5.0
+ from gguf.gguf_reader import GGUFReader
+
+ gguf_model = GGUFReader(os.path.join(quantized_model_path, gguf_file))
+ assert gguf_model.get_tensor(2).name == "blk.0.attn_v.weight"
+ assert gguf_model.get_tensor(2).tensor_type.name == "Q4_K"
+ assert gguf_model.get_tensor(9).name == "blk.0.ffn_up_exps.weight"
+ assert gguf_model.get_tensor(9).tensor_type.name == "Q2_K"
+
+ shutil.rmtree(saved_tiny_model_path, ignore_errors=True)
+
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested for CI")
+ def test_gguf_baseline(self):
+ model_name = get_model_path("Qwen/Qwen2.5-1.5B-Instruct")
+ autoround = AutoRound(
+ model_name,
+ bits=3,
+ group_size=16,
+ sym=True,
+ iters=0,
+ nsamples=8,
+ seqlen=2,
+ data_type="rtn_int_sym_dq",
+ super_group_size=16,
+ super_bits=6,
+ disable_opt_rtn=True,
+ )
+ quantized_model_path = self.save_dir
+ autoround.quantize_and_save(output_dir=quantized_model_path, inplace=False, format="fake")
+ eval_generated_prompt(quantized_model_path)
diff --git a/test/test_cuda/export/test_llmc_format.py b/test/test_cuda/export/test_llmc_format.py
new file mode 100644
index 000000000..fe2dddc6f
--- /dev/null
+++ b/test/test_cuda/export/test_llmc_format.py
@@ -0,0 +1,109 @@
+import shutil
+
+import pytest
+import torch
+import transformers
+
+from auto_round import AutoRound
+from auto_round import schemes as ar_schemes
+
+from ...helpers import eval_generated_prompt, get_model_path, is_cuda_support_fp8
+
+
+class TestAutoRound:
+
+ @pytest.fixture(autouse=True, scope="class")
+ def setup_and_teardown_class(self):
+ # ===== SETUP (setup_class) =====
+ print("[Setup] Running before any test in class")
+
+ # Yield to hand control to the test methods
+ yield
+
+ # ===== TEARDOWN (teardown_class) =====
+ print("[Teardown] Running after all tests in class")
+ shutil.rmtree("runs", ignore_errors=True)
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
+ @pytest.mark.skip_ci(reason="Cannot test all case in CI; time-consuming")
+ def test_fp8input_mxfp4_llmcompressor_format(self, dataloader, tiny_fp8_qwen_model_path, mock_fp8_capable_device):
+ scheme = "mxfp4"
+ ar = AutoRound(
+ model=tiny_fp8_qwen_model_path,
+ iters=1,
+ seqlen=2,
+ scheme=scheme,
+ dataset=dataloader,
+ )
+ print(ar.model)
+ compressed_model, _ = ar.quantize_and_save(output_dir=self.save_dir, format="llm_compressor")
+ tmp_layer = compressed_model.model.layers[1].self_attn.q_proj
+ assert (
+ hasattr(tmp_layer, "weight_scale")
+ and hasattr(tmp_layer, "weight_packed")
+ and tmp_layer.weight_scale.dtype is torch.uint8
+ and tmp_layer.weight_scale.shape[0] == 2048
+ ), "Illegal MXFP4 packing name or data_type or shape"
+ quantization_config = transformers.AutoConfig.from_pretrained(
+ self.save_dir, trust_remote_code=True
+ ).quantization_config
+ assert (
+ quantization_config["format"] == "float-quantized"
+ and quantization_config["config_groups"]["group_0"]["weights"]["is_mx"] is True
+ and quantization_config["config_groups"]["group_0"]["weights"]["num_bits"] == 4
+ ), f"Invalid MXFP4 quantization configuration: {quantization_config}"
+
+ @pytest.mark.skip_ci(reason="Cannot test all case in CI; time-consuming")
+ def test_nvfp4_llmcompressor_format(self, tiny_opt_model_path, dataloader):
+ scheme = "nvfp4"
+ autoround = AutoRound(
+ tiny_opt_model_path,
+ scheme=scheme,
+ iters=2,
+ seqlen=2,
+ dataset=dataloader,
+ )
+ quantized_model_path = self.save_dir
+ compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="llm_compressor")
+ tmp_layer = compressed_model.model.decoder.layers[1].self_attn.q_proj
+ assert (
+ hasattr(tmp_layer, "weight_scale")
+ and hasattr(tmp_layer, "weight_global_scale")
+ and hasattr(tmp_layer, "input_global_scale")
+ and tmp_layer.weight_packed.dtype is torch.uint8
+ and tmp_layer.weight_scale.dtype is torch.float8_e4m3fn
+ and tmp_layer.weight_scale.shape[0] == 768
+ ), "Illegal NVFP4 packing name or data_type or shape"
+ quantization_config = transformers.AutoConfig.from_pretrained(
+ quantized_model_path, trust_remote_code=True
+ ).quantization_config
+ assert (
+ quantization_config["format"] == "nvfp4-pack-quantized"
+ and quantization_config["config_groups"]["group_0"]["input_activations"]["num_bits"] == 4
+ ), f"Invalid NVFP4 quantization configuration: {quantization_config}"
+
+ @pytest.mark.skip_ci(reason="Cannot test all case in CI; time-consuming")
+ def test_fp8_block_llm_compressor_format(self, tiny_qwen_model_path, dataloader):
+ model_name = get_model_path("Qwen/Qwen3-0.6B")
+
+ scheme = "FP8_BLOCK"
+ autoround = AutoRound(
+ model_name,
+ scheme=scheme,
+ iters=0,
+ disable_opt_rtn=True,
+ )
+ quantized_model_path = self.save_dir
+ compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="llm_compressor")
+ tmp_layer = compressed_model.model.layers[1].self_attn.q_proj
+ assert hasattr(tmp_layer, "weight_scale")
+ assert tmp_layer.weight.dtype is torch.float8_e4m3fn
+ assert list(tmp_layer.weight_scale.shape) == [16, 8]
+ assert compressed_model.config.quantization_config["quant_method"] == "compressed-tensors"
+ if is_cuda_support_fp8():
+ eval_generated_prompt(quantized_model_path, device="cuda")
diff --git a/test/test_cuda/integrations/test_sglang.py b/test/test_cuda/integrations/test_sglang.py
index a063ebfe1..2bee14bd5 100644
--- a/test/test_cuda/integrations/test_sglang.py
+++ b/test/test_cuda/integrations/test_sglang.py
@@ -1,3 +1,4 @@
+import gc
import json
import shutil
import sys
@@ -13,9 +14,14 @@ from ...helpers import get_model_path, opt_name_or_path
class TestAutoRound:
- save_dir = "./saved"
model_name = opt_name_or_path
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
@pytest.fixture(autouse=True, scope="class")
def setup_and_teardown_class(self):
# ===== SETUP (setup_class) =====
@@ -26,17 +32,22 @@ class TestAutoRound:
# ===== TEARDOWN (teardown_class) =====
print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
def _run_sglang_inference(self, model_path: Path):
llm = sgl.Engine(
- model_path=str(model_path), mem_fraction_static=0.7, disable_piecewise_cuda_graph=True, cuda_graph_bs=[1]
+ model_path=str(model_path), mem_fraction_static=0.5, disable_piecewise_cuda_graph=True, cuda_graph_bs=[1]
)
- prompts = ["Hello, my name is"]
- sampling_params = {"temperature": 0.6, "top_p": 0.95}
- outputs = llm.generate(prompts, sampling_params)
- return outputs[0]["text"]
+ try:
+ prompts = ["Hello, my name is"]
+ sampling_params = {"temperature": 0.6, "top_p": 0.95}
+ outputs = llm.generate(prompts, sampling_params)
+ return outputs[0]["text"]
+ finally:
+ llm.shutdown()
+ del llm
+ gc.collect()
+ torch.cuda.empty_cache()
def test_ar_format_sglang(self, dataloader):
autoround = AutoRound(
@@ -58,8 +69,6 @@ class TestAutoRound:
assert "!!!" not in generated_text
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
def test_mixed_ar_format_sglang(self, dataloader):
layer_config = {
"self_attn": {"bits": 8},
@@ -98,6 +107,7 @@ class TestAutoRound:
shutil.rmtree(self.save_dir, ignore_errors=True)
+ @pytest.mark.skip_ci(reason="Cannot work well in CI env")
def test_awq_format_sglang(self, dataloader):
autoround = AutoRound(
self.model_name,
@@ -117,5 +127,3 @@ class TestAutoRound:
print(generated_text)
assert "!!!" not in generated_text
-
- shutil.rmtree(self.save_dir, ignore_errors=True)
diff --git a/test/test_cuda/integrations/test_transformers.py b/test/test_cuda/integrations/test_transformers.py
deleted file mode 100644
index 7adbe43d7..000000000
--- a/test/test_cuda/integrations/test_transformers.py
+++ /dev/null
@@ -1,221 +0,0 @@
-# Copyright 2025 The HuggingFace Team. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-import gc
-import os
-import tempfile
-
-import pytest
-from transformers import AutoModelForCausalLM, AutoRoundConfig, AutoTokenizer
-from transformers.testing_utils import (
- require_accelerate,
- require_torch_gpu,
- require_torch_multi_gpu,
- slow,
- torch_device,
-)
-from transformers.utils import is_torch_available
-
-from ...envs import is_ipex_available
-from ...helpers import get_model_path
-
-if is_torch_available():
- import torch
-
-
-# @slow
-@require_torch_gpu
-@require_accelerate
-class TestAutoRound:
- model_name = "OPEA/Qwen2.5-1.5B-Instruct-int4-sym-inc"
- input_text = "There is a girl who likes adventure,"
- EXPECTED_OUTPUTS = set()
- ## Different backends may produce slight variations in output
- EXPECTED_OUTPUTS.add(
- "There is a girl who likes adventure, and she has been exploring the world "
- "for many years. She travels to different countries and cultures, trying new "
- "things every day. One of her favorite places to visit is a small village in "
- "the mountains where"
- )
- EXPECTED_OUTPUTS.add(
- "There is a girl who likes adventure, and she has been exploring the world for many years. She has visited every country in Europe and has even traveled to some of the most remote parts of Africa. She enjoys hiking through the mountains and discovering"
- )
- # transformers 5.0.0
- EXPECTED_OUTPUTS.add(
- "There is a girl who likes adventure, and she has been exploring the world for many years. She has visited every country in Europe and has even traveled to some of the most remote parts of Africa. She has also climbed mountains, swum"
- )
- # transformers 5.1.0
- EXPECTED_OUTPUTS.add(
- "There is a girl who likes adventure, and she has been exploring the world for many years. She has visited every country in Europe and has even traveled to some of the most remote parts of Africa. She has also climbed mountains and explored caves"
- )
-
- device_map = "cuda"
-
- # called only once for all test in this class
- @classmethod
- def setup_class(cls):
- """
- Setup quantized model
- """
- torch.cuda.synchronize()
- cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name)
- cls.quantized_model = AutoModelForCausalLM.from_pretrained(
- cls.model_name, device_map=cls.device_map, torch_dtype=torch.float16
- )
-
- def tearDown(self):
- gc.collect()
- torch.cuda.empty_cache()
- gc.collect()
-
- def test_quantized_model(self):
- """
- Simple test that checks if the quantized model is working properly
- """
- input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
- output = self.quantized_model.generate(**input_ids, max_new_tokens=40, do_sample=False)
- assert self.tokenizer.decode(output[0], skip_special_tokens=True) in self.EXPECTED_OUTPUTS
-
- def test_raise_if_non_quantized(self, tiny_opt_model_path):
- model_id = tiny_opt_model_path
- quantization_config = AutoRoundConfig(bits=4)
- with pytest.raises(ValueError):
- _ = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config)
-
- def test_quantized_model_bf16(self):
- """
- Simple test that checks if the quantized model is working properly with bf16
- """
- input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
- quantization_config = AutoRoundConfig(backend="triton")
- quantized_model = AutoModelForCausalLM.from_pretrained(
- self.model_name,
- torch_dtype=torch.bfloat16,
- device_map=self.device_map,
- quantization_config=quantization_config,
- )
-
- output = quantized_model.generate(**input_ids, max_new_tokens=40, do_sample=False)
- output_sentence = self.tokenizer.decode(output[0], skip_special_tokens=True)
- assert output_sentence in self.EXPECTED_OUTPUTS
-
- @pytest.mark.skipif(not is_ipex_available(), reason="test requires intel-extension-for-pytorch")
- def test_quantized_model_on_cpu(self):
- """
- Simple test that checks if the quantized model is working properly
- """
- input_ids = self.tokenizer(self.input_text, return_tensors="pt")
-
- quantized_model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto")
- output = quantized_model.generate(**input_ids, max_new_tokens=40, do_sample=False)
-
- assert self.tokenizer.decode(output[0], skip_special_tokens=True) in self.EXPECTED_OUTPUTS
-
- def test_save_pretrained(self):
- """
- Simple test that checks if the quantized model is working properly after being saved and loaded
- """
-
- ## some backends like marlin/ipex will repack the weight that caused the weight shape changed
- with tempfile.TemporaryDirectory() as tmpdirname:
- quantization_config = AutoRoundConfig(backend="triton")
- quantized_model = AutoModelForCausalLM.from_pretrained(
- self.model_name,
- device_map=self.device_map,
- torch_dtype=torch.float16,
- quantization_config=quantization_config,
- )
-
- quantized_model.save_pretrained(tmpdirname)
- model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="cuda")
-
- input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)
-
- output = model.generate(**input_ids, max_new_tokens=40, do_sample=False)
- assert self.tokenizer.decode(output[0], skip_special_tokens=True) in self.EXPECTED_OUTPUTS
-
- @require_torch_multi_gpu
- def test_quantized_model_multi_gpu(self):
- """
- Simple test that checks if the quantized model is working properly with multiple GPUs
- """
- quantization_config = AutoRoundConfig(backend="triton")
- quantized_model = AutoModelForCausalLM.from_pretrained(
- self.model_name, device_map="auto", quantization_config=quantization_config, torch_dtype="auto"
- )
- input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(quantized_model.device)
- output = quantized_model.generate(**input_ids, max_new_tokens=40, do_sample=False)
- assert self.tokenizer.decode(output[0], skip_special_tokens=True) in self.EXPECTED_OUTPUTS
-
- def test_convert_from_gptq(self):
- """
- Simple test that checks if auto-round work properly with gptq format
- """
- model_name = "ybelkada/opt-125m-gptq-4bit"
-
- quantization_config = AutoRoundConfig()
-
- model = AutoModelForCausalLM.from_pretrained(
- model_name, device_map="cuda", quantization_config=quantization_config, torch_dtype="auto"
- )
- tokenizer = AutoTokenizer.from_pretrained(model_name)
-
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- tokenizer.decode(model.generate(**inputs, max_new_tokens=5)[0])
-
- @pytest.mark.skipif(not is_ipex_available(), reason="test requires intel-extension-for-pytorch")
- def test_convert_from_awq_cpu(self):
- """
- Simple test that checks if auto-round work properly with awq format
- """
- model_name = "casperhansen/opt-125m-awq"
-
- quantization_config = AutoRoundConfig()
-
- model = AutoModelForCausalLM.from_pretrained(
- model_name, device_map="cpu", quantization_config=quantization_config, torch_dtype="auto"
- )
- tokenizer = AutoTokenizer.from_pretrained(model_name)
-
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- tokenizer.decode(model.generate(**inputs, max_new_tokens=5)[0])
-
- def test_mixed_bits(self):
- """
- Simple test that checks if auto-round work properly with mixed bits
- """
- model_name = get_model_path("facebook/opt-125m")
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto")
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- layer_config = {
- "model.decoder.layers.0.self_attn.k_proj": {"bits": 8},
- "model.decoder.layers.6.self_attn.out_proj": {"bits": 2, "group_size": 32},
- }
-
- bits, group_size, sym = 4, 128, True
- from auto_round import AutoRound
-
- autoround = AutoRound(model, tokenizer, bits=bits, group_size=group_size, sym=sym, layer_config=layer_config)
- with tempfile.TemporaryDirectory() as tmpdirname:
- autoround.quantize_and_save(output_dir=tmpdirname)
- model = AutoModelForCausalLM.from_pretrained(tmpdirname, torch_dtype=torch.float16, device_map="cuda")
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- tokenizer.decode(model.generate(**inputs, max_new_tokens=5)[0])
-
-
-# FAILED export/test_gguf.py::TestAutoRound::test_gguf_format - AssertionError: qwen2 tuning fail
-# FAILED export/test_gguf.py::TestAutoRound::test_all_format - SystemExit: 1
-# FAILED export/test_gguf.py::TestAutoRound::test_vlm_gguf - AttributeError: 'Qwen2VLForConditionalGeneration' object has no attribute 'last_layer_name_to_block_name'
diff --git a/test/test_cuda/integrations/test_vllm.py b/test/test_cuda/integrations/test_vllm.py
index eafdda617..895e3c9c3 100644
--- a/test/test_cuda/integrations/test_vllm.py
+++ b/test/test_cuda/integrations/test_vllm.py
@@ -9,6 +9,7 @@ Run `pytest test/test_cuda/test_vllm.py`.
import os
import shutil
+import sys
import pytest
from vllm import LLM, SamplingParams
@@ -60,6 +61,95 @@ def test_auto_round(model):
assert "Paris" in generated_text
+def test_mixed_autoround_format_vllm(tiny_opt_model_path, dataloader, tmp_path):
+ layer_config = {
+ "self_attn": {"bits": 8},
+ "lm_head": {"bits": 16},
+ }
+ autoround = AutoRound(
+ tiny_opt_model_path,
+ scheme="W4A16",
+ iters=0,
+ disable_opt_rtn=True,
+ layer_config=layer_config,
+ )
+ autoround.quantize()
+ quantized_model_path = str(tmp_path / "saved")
+ autoround.save_quantized(output_dir=quantized_model_path, format="auto_round")
+
+ # verify loading.
+ llm = LLM(
+ model=quantized_model_path,
+ trust_remote_code=True,
+ tensor_parallel_size=1,
+ allow_deprecated_quantization=True,
+ )
+
+
+def test_mixed_llmcompressor_format_vllm(tiny_opt_model_path, dataloader, tmp_path):
+ layer_config = {
+ "self_attn": {"bits": 16, "act_bits": 16},
+ "lm_head": {"bits": 16, "act_bits": 16},
+ "fc1": {"bits": 16, "act_bits": 16},
+ }
+ autoround = AutoRound(
+ tiny_opt_model_path,
+ scheme="NVFP4",
+ iters=0,
+ disable_opt_rtn=True,
+ layer_config=layer_config,
+ )
+ quantized_model_path = str(tmp_path / "saved")
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="llm_compressor")
+
+ # verify loading.
+ llm = LLM(
+ model=quantized_model_path,
+ trust_remote_code=True,
+ tensor_parallel_size=1,
+ allow_deprecated_quantization=True,
+ )
+
+
+# ================ Test Evaluation function ===============
+
+
+ not os.path.exists("/usr/bin/nvidia-smi") and not os.path.exists("/usr/local/cuda"), reason="CUDA not available"
+)
+class TestVllmEvaluation:
+ """Test VLLM backend evaluation functionality."""
+
+ def test_vllm_backend_with_custom_args(self, tiny_opt_model_path):
+ """Test vllm backend evaluation with custom vllm_args parameter."""
+ python_path = sys.executable
+
+ os.environ["VLLM_SKIP_WARMUP"] = "true"
+ os.environ["NCCL_ASYNC_ERROR_HANDLING"] = "1"
+ os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
+
+ # Test with custom vllm_args
+ cmd = f"{python_path} -m auto_round --model {tiny_opt_model_path} --eval --tasks lambada_openai --eval_bs 128 --eval_backend vllm --limit 10 --vllm_args tensor_parallel_size=1,gpu_memory_utilization=0.2,max_model_len=1024"
+
+ ret = os.system(cmd)
+
+ assert ret == 0, f"vllm evaluation with custom args failed (rc={ret})"
+
+ def test_vllm_backend_with_quantization_iters_0(self, tiny_opt_model_path):
+ """Test vllm evaluation with iters=0 (quantization without fine-tuning)."""
+ python_path = sys.executable
+
+ os.environ["VLLM_SKIP_WARMUP"] = "true"
+ os.environ["NCCL_ASYNC_ERROR_HANDLING"] = "1"
+ os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
+
+ cmd = f"{python_path} -m auto_round --model {tiny_opt_model_path} --iters 0 --disable_opt_rtn --tasks lambada_openai --eval_bs 8 --eval_backend vllm --limit 10"
+
+ ret = os.system(cmd)
+
+ assert ret == 0, f"vllm evaluation with iters=0 failed (rc={ret})"
+
+
@pytest.mark.skipif(
not current_platform.is_cuda(),
reason="only supports CUDA backend.",
@@ -90,4 +180,3 @@ def test_auto_round_awq_format_vllm():
generated_text = outputs[0].outputs[0].text
print(generated_text)
assert len(generated_text.strip()) > 0, "vLLM AWQ inference produced empty output"
- shutil.rmtree(save_dir, ignore_errors=True)
diff --git a/test/test_cuda/models/test_conv1d.py b/test/test_cuda/models/test_conv1d.py
index deae349b3..40bb455a2 100644
--- a/test/test_cuda/models/test_conv1d.py
+++ b/test/test_cuda/models/test_conv1d.py
@@ -12,22 +12,16 @@ from ...helpers import get_model_path, get_tiny_model, model_infer
class TestQuantizationConv1d:
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
- # Yield to hand control to the test methods
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- @classmethod
- def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
+ @pytest.fixture(autouse=True, scope="class")
+ def setup_and_teardown_class(self):
+ yield
shutil.rmtree("runs", ignore_errors=True)
@require_gptqmodel
@@ -50,8 +44,8 @@ class TestQuantizationConv1d:
)
autoround.quantize()
- autoround.save_quantized("./saved")
+ autoround.save_quantized(self.save_dir)
- model = AutoModelForCausalLM.from_pretrained("./saved", device_map="cuda", trust_remote_code=True)
- tokenizer = AutoTokenizer.from_pretrained("./saved", trust_remote_code=True)
+ model = AutoModelForCausalLM.from_pretrained(self.save_dir, device_map="cuda", trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(self.save_dir, trust_remote_code=True)
model_infer(model, tokenizer)
diff --git a/test/test_cuda/models/test_diffusion.py b/test/test_cuda/models/test_diffusion.py
index 703653be7..2f2a1b940 100644
--- a/test/test_cuda/models/test_diffusion.py
+++ b/test/test_cuda/models/test_diffusion.py
@@ -11,86 +11,86 @@ from PIL import Image
from auto_round import AutoRoundDiffusion
from ...envs import require_gptqmodel, require_optimum, require_vlm_env
-from ...helpers import transformers_version
+from ...helpers import get_captions_dataset_path, get_model_path, transformers_version
class TestAutoRound:
- model_name = "/dataset/FLUX.1-dev"
+ model_name = get_model_path("black-forest-labs/FLUX.1-dev")
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
@pytest.fixture(autouse=True, scope="class")
def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
yield
-
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
- @require_optimum
- @pytest.mark.skipif(
- transformers_version >= version.parse("5.0.0"),
- reason="cannot import name 'MT5Tokenizer' from 'transformers', https://github.com/huggingface/diffusers/issues/13035",
- )
- def test_diffusion_tune(self):
+ def test_diffusion_rtn(self):
from diffusers import AutoPipelineForText2Image
## load the model
- pipe = AutoPipelineForText2Image.from_pretrained(self.model_name).to("cuda")
- model = pipe.transformer
-
- layer_config = {}
- # skip some layers since it takes much time
- for n, m in model.named_modules():
- if m.__class__.__name__ != "Linear":
- continue
- match = re.search(r"blocks\.(\d+)", n)
- if match and int(match.group(1)) > 0:
- layer_config[n] = {"bits": 16, "act_bits": 16}
+ pipe = AutoPipelineForText2Image.from_pretrained(self.model_name)
+ # build tiny model for testing since the full model is too large to quantize and evaluate in CI
+ pipe.transformer.transformer_blocks = pipe.transformer.transformer_blocks[:2]
+ pipe.transformer.single_transformer_blocks = pipe.transformer.single_transformer_blocks[:2]
## quantize the model
autoround = AutoRoundDiffusion(
pipe,
tokenizer=None,
scheme="MXFP4",
- iters=1,
- nsamples=1,
+ iters=0,
+ disable_opt_rtn=True,
num_inference_steps=2,
- layer_config=layer_config,
- dataset="/dataset/captions_source.tsv",
+ dataset=get_captions_dataset_path(),
)
# skip model saving since it takes much time
autoround.quantize()
- @pytest.mark.skipif(
- transformers_version >= version.parse("5.0.0"),
- reason="cannot import name 'MT5Tokenizer' from 'transformers', https://github.com/huggingface/diffusers/issues/13035",
- )
- def test_diffusion_rtn(self):
+ @pytest.mark.skip_ci(reason="Tuning will OOM in CI; Only tiny model is suggested") # skip this test in CI
+ @require_optimum
+ def test_diffusion_tune(self):
from diffusers import AutoPipelineForText2Image
## load the model
pipe = AutoPipelineForText2Image.from_pretrained(self.model_name)
+ model = pipe.transformer
+ # build tiny model for testing since the full model is too large to quantize and evaluate in CI
+ pipe.transformer.transformer_blocks = pipe.transformer.transformer_blocks[:2]
+ pipe.transformer.single_transformer_blocks = pipe.transformer.single_transformer_blocks[:2]
+
+ layer_config = {}
+ # skip some layers since it takes much time
+ for n, m in model.named_modules():
+ if m.__class__.__name__ != "Linear":
+ continue
+ match = re.search(r"blocks\.(\d+)", n)
+ if match and int(match.group(1)) > 0:
+ layer_config[n] = {"bits": 16, "act_bits": 16}
## quantize the model
+ # https://raw.githubusercontent.com/mlcommons/inference/refs/heads/master/text_to_image/coco2014/captions/captions_source.tsv
autoround = AutoRoundDiffusion(
pipe,
tokenizer=None,
scheme="MXFP4",
- iters=0,
+ iters=1,
+ nsamples=1,
num_inference_steps=2,
- dataset="/dataset/captions_source.tsv",
+ layer_config=layer_config,
+ dataset=get_captions_dataset_path(),
)
# skip model saving since it takes much time
autoround.quantize()
+ @pytest.mark.skip_ci(reason="Download large model; Time-consuming")
def test_diffusion_model_checker(self):
from auto_round.utils import is_diffusion_model
- assert is_diffusion_model("/dataset/FLUX.1-dev")
- assert is_diffusion_model("/models/stable-diffusion-2-1")
- assert is_diffusion_model("/models/stable-diffusion-xl-base-1.0")
- assert is_diffusion_model("/models/Qwen3-8B") is False
+ assert is_diffusion_model(get_model_path("black-forest-labs/FLUX.1-dev"))
+ assert is_diffusion_model(get_model_path("sd2-community/stable-diffusion-2-1"))
+ assert is_diffusion_model(get_model_path("stabilityai/stable-diffusion-xl-base-1.0"))
+ assert is_diffusion_model(get_model_path("Qwen/Qwen3-8B")) is False
diff --git a/test/test_cuda/models/test_fp8_model.py b/test/test_cuda/models/test_fp8_model.py
index 5b7962f7b..1b7e97e4d 100644
--- a/test/test_cuda/models/test_fp8_model.py
+++ b/test/test_cuda/models/test_fp8_model.py
@@ -1,28 +1,127 @@
+import os
import shutil
import pytest
import torch
-import torch.nn as nn
-from transformers import AutoConfig, AutoModelForCausalLM, AutoProcessor, AutoTokenizer
+from packaging import version
+from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
from auto_round import AutoRound
+from auto_round.utils import llm_load_model
+from auto_round.utils.weight_handler import (
+ ModuleWeightType,
+ check_and_mark_quantized_module,
+ convert_module_to_hp_if_necessary,
+)
+from ...helpers import evaluate_accuracy, generate_prompt, get_model_path, get_tiny_model, transformers_version
-def setup_qwen_fp8():
- """Fixture to set up the GPT-OSS model and tokenizer."""
- model_name = "INC4AI/Qwen3-30B-A3B-Instruct-2507-FP8-2Layers"
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
- config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
- # model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True)
- output_dir = "test_quantized_qwen3_fp8_moe_mxfp"
- return tokenizer, output_dir, config, model_name
+class TestAutoRound:
-def test_qwen3_fp8_moe_mxfp(setup_qwen_fp8):
- tokenizer, output_dir, config, model_name = setup_qwen_fp8
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
+ @pytest.fixture(autouse=True, scope="class")
+ def setup_and_teardown_class(self):
+ yield
+ shutil.rmtree("runs", ignore_errors=True)
+
+ def test_small_model_rtn_generation(self, mock_fp8_capable_device, tiny_fp8_qwen_model_path):
+ ar = AutoRound(tiny_fp8_qwen_model_path, iters=0, disable_opt_rtn=True)
+ ar.quantize_and_save(output_dir=self.save_dir)
+ model = AutoModelForCausalLM.from_pretrained(self.save_dir, torch_dtype="auto", trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
+ generate_prompt(model, tokenizer)
+
+ def test_gguf_imatrix(self, mock_fp8_capable_device, tiny_fp8_qwen_model_path):
+ ar = AutoRound(tiny_fp8_qwen_model_path, iters=0)
+ ar.quantize_and_save(format="gguf:q2_k_s", output_dir=self.save_dir)
+ # from llama_cpp import Llama
+ #
+ # gguf_file = os.listdir("saved/Qwen3-0.6B-FP8/-gguf")[0]
+ # llm = Llama(f"saved/Qwen2.5-0.5B-Instruct-gguf/{gguf_file}", n_gpu_layers=-1)
+ # output = llm("There is a girl who likes adventure,", max_tokens=32)
+ # print(output)
+ # shutil.rmtree("./saved", ignore_errors=True)
+ # model = AutoModelForCausalLM.from_pretrained(self.save_dir, torch_dtype="auto", trust_remote_code=True)
+ # tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
+ # text = "There is a girl who likes adventure,"
+ # inputs = tokenizer(text, return_tensors="pt").to(model.device)
+ # print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
+
+ @pytest.mark.skip_ci(reason="Triton issue; time-consuming")
+ def test_small_model_rtn(self, mock_fp8_capable_device):
+ model_name = get_model_path("Qwen/Qwen3-0.6B-FP8")
+ ar = AutoRound(model=model_name, iters=0)
+ _, folder = ar.quantize_and_save(output_dir=self.save_dir)
+ evaluate_accuracy(self.save_dir, threshold=0.25)
+
+ @pytest.mark.skip_ci(reason="Triton issue; time-consuming")
+ def test_small_model_iters1(self, mock_fp8_capable_device):
+ model_name = get_model_path("Qwen/Qwen3-0.6B-FP8")
+ ar = AutoRound(model=model_name, iters=1)
+ _, folder = ar.quantize_and_save(output_dir=self.save_dir)
+ evaluate_accuracy(self.save_dir, threshold=0.25)
+
+ @pytest.mark.skip_ci(reason="Triton issue; time-consuming")
+ def test_medium_model_rtn(self, mock_fp8_capable_device):
+ model_name = get_model_path("Qwen/Qwen3-0.6B-FP8")
+ ar = AutoRound(model=model_name, iters=0)
+ _, folder = ar.quantize_and_save(output_dir=self.save_dir)
+ evaluate_accuracy(self.save_dir, threshold=0.33)
+
+ @pytest.mark.skip_ci(reason="Triton issue; time-consuming")
+ def test_medium_model_rtn_with_lm_head(self, mock_fp8_capable_device):
+ model_name = get_model_path("Qwen/Qwen3-0.6B-FP8")
+ layer_config = {"lm_head": {"bits": 4}}
+ ar = AutoRound(model=model_name, iters=0, layer_config=layer_config)
+ _, folder = ar.quantize_and_save(output_dir=self.save_dir)
+ evaluate_accuracy(self.save_dir, threshold=0.33)
+
+ def test_fp8_model_gguf_q4(self, mock_fp8_capable_device, tiny_fp8_qwen_model_path):
+ from llama_cpp import Llama
+
+ ar = AutoRound(tiny_fp8_qwen_model_path, iters=0, disable_opt_rtn=True)
+ ar.quantize_and_save(output_dir=self.save_dir, format="gguf:q4_0")
+ for file in os.listdir(self.save_dir):
+ if file.endswith(".gguf"):
+ gguf_file = file
+ llm = Llama(f"{self.save_dir}/{gguf_file}", n_gpu_layers=-1)
+ output = llm("There is a girl who likes adventure,", max_tokens=32)
+ print(output)
+
+ @pytest.mark.skip_ci(reason="Not necessary to test all options in CI")
+ def test_fp8_model_gguf_q3(self, mock_fp8_capable_device, tiny_fp8_qwen_model_path):
+ from llama_cpp import Llama
+
+ ar = AutoRound(tiny_fp8_qwen_model_path, iters=1)
+ ar.quantize_and_save(output_dir=self.save_dir, format="gguf:q3_k_s")
+ for file in os.listdir(self.save_dir):
+ if file.endswith(".gguf"):
+ gguf_file = file
+ llm = Llama(f"{self.save_dir}/{gguf_file}", n_gpu_layers=-1)
+ output = llm("There is a girl who likes adventure,", max_tokens=32)
+ print(output)
+
+ @pytest.mark.skip_ci(reason="Not necessary to test all options in CI")
+ @pytest.mark.parametrize("scheme", ["MXFP4", "NVFP4"])
+ def test_diff_datatype(self, scheme, tiny_fp8_qwen_model_path, mock_fp8_capable_device):
+ model_name = tiny_fp8_qwen_model_path
+ print(f"Testing scheme: {scheme}")
+ ar = AutoRound(model_name, iters=0, scheme=scheme, disable_opt_rtn=True, nsamples=2)
+ ar.quantize_and_save(output_dir=self.save_dir)
+ model = AutoModelForCausalLM.from_pretrained(self.save_dir, torch_dtype="auto", trust_remote_code=True)
+ assert model is not None, f"Failed to load model for scheme {scheme}"
+
+
+def test_qwen3_fp8_moe_mxfp(tiny_fp8_qwen_moe_model_path, mock_fp8_capable_device):
+ output_dir = "./tmp"
autoround = AutoRound(
- model_name,
+ tiny_fp8_qwen_moe_model_path,
scheme="MXFP4",
nsamples=2,
seqlen=32,
@@ -31,8 +130,6 @@ def test_qwen3_fp8_moe_mxfp(setup_qwen_fp8):
quantized_model, _ = autoround.quantize_and_save(format="auto_round", output_dir=output_dir)
assert quantized_model is not None, "Quantized model should not be None."
loaded_model = AutoModelForCausalLM.from_pretrained(output_dir)
- loaded_model.to("cuda")
- quantized_model.to("cuda")
for n, m in quantized_model.named_modules():
if m.__class__.__name__ == "QuantLinear":
loaded_m = loaded_model.get_submodule(n)
@@ -42,14 +139,17 @@ def test_qwen3_fp8_moe_mxfp(setup_qwen_fp8):
if "experts" in m.__class__.__name__.lower():
for sub_n, sub_m in m.named_modules():
assert sub_m.__class__.__name__ == "QuantLinear", f"Module {n}.{sub_n} is not quantized."
- inp = torch.randint(0, 100, (1, 64)).to("cuda")
- with torch.inference_mode():
- loaded_out = loaded_model(inp)
-
- # test generation
- tokenizer = AutoTokenizer.from_pretrained(output_dir)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(device=loaded_model.device)
- print(tokenizer.decode(loaded_model.generate(**inputs, max_new_tokens=50)[0]))
- # clean the output directory after test
shutil.rmtree(output_dir, ignore_errors=True)
+
+
+# requires GPU to load FP8Linear
+class TestFP8Linear:
+ def test_fp8_input(self, mock_fp8_capable_device):
+ model = get_tiny_model(get_model_path("Qwen/Qwen3-0.6B-FP8"))
+ assert (
+ type(model.model.layers[0].mlp.up_proj).__name__ == "FP8Linear"
+ ), "Model does not contain FP8Linear layers"
+ detected_types = check_and_mark_quantized_module(model)
+ assert ModuleWeightType.FP8 in detected_types
+ model = convert_module_to_hp_if_necessary(model)
+ assert type(model.model.layers[0].mlp.up_proj) is torch.nn.Linear, "FP8Linear layer was not converted to Linear"
diff --git a/test/test_cuda/models/test_get_block_name.py b/test/test_cuda/models/test_get_block_name.py
index 295c56946..4f26987ec 100644
--- a/test/test_cuda/models/test_get_block_name.py
+++ b/test/test_cuda/models/test_get_block_name.py
@@ -17,9 +17,10 @@ from transformers import (
from auto_round import AutoRound
from auto_round.utils import get_block_names, is_pure_text_model
-from ...helpers import transformers_version
+from ...helpers import get_model_path, transformers_version
[email protected]_ci(reason="Only tiny model is suggested")
class TestAutoRound:
@classmethod
def setup_class(self):
@@ -38,7 +39,7 @@ class TestAutoRound:
assert block_name == expected_block_names
def test_glm4(self):
- model_name = "/models/glm-4-9b-chat-hf"
+ model_name = get_model_path("THUDM/glm-4-9b-chat-hf")
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
@@ -49,7 +50,7 @@ class TestAutoRound:
assert is_pure_text_model(model), "Expected model to be pure text model"
def test_opt_125m(self):
- model_name = "/models/opt-125m"
+ model_name = get_model_path("facebook/opt-125m")
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.decoder.layers"], [12])
@@ -57,56 +58,56 @@ class TestAutoRound:
assert is_pure_text_model(model)
def test_Qwen(self):
- model_name = "/models/Qwen2.5-7B-Instruct"
+ model_name = get_model_path("Qwen/Qwen2.5-7B-Instruct")
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.layers"], [28])
assert is_pure_text_model(model)
def test_phi4(self):
- model_name = "/models/phi-4"
+ model_name = get_model_path("microsoft/phi-4")
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.layers"], [40])
assert is_pure_text_model(model)
def test_llama3(self):
- model_name = "/models/Meta-Llama-3.1-8B-Instruct"
+ model_name = get_model_path("meta-llama/Meta-Llama-3.1-8B-Instruct")
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.layers"], [32])
assert is_pure_text_model(model)
# def test_mixtral(self):
- # model_name = "/models/Mixtral-8x7B-Instruct-v0.1"
+ # model_name = get_model_path("mistralai/Mixtral-8x7B-Instruct-v0.1")
# model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
# block_names = get_block_names(model)
# self.check_block_names(block_names, ["model.layers"], [32])
# assert is_pure_text_model(model)
def test_falcon(self):
- model_name = "/models/Falcon3-7B-Instruct"
+ model_name = get_model_path("tiiuae/Falcon3-7B-Instruct")
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.layers"], [28])
assert is_pure_text_model(model)
def test_orca(self):
- model_name = "/models/Orca-2-7b"
+ model_name = get_model_path("microsoft/Orca-2-7b")
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.layers"], [32])
assert is_pure_text_model(model)
def test_OLMo(self):
- model_name = "/models/OLMo-2-1124-7B-Instruct"
+ model_name = get_model_path("allenai/OLMo-2-1124-7B-Instruct")
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.layers"], [32])
assert is_pure_text_model(model)
def test_Qwen2VL(self):
- model_name = "/models/Qwen2-VL-2B-Instruct"
+ model_name = get_model_path("Qwen/Qwen2-VL-2B-Instruct")
model = Qwen2VLForConditionalGeneration.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.language_model.layers"], [28])
@@ -116,7 +117,7 @@ class TestAutoRound:
assert not is_pure_text_model(model)
def test_Llama32(self):
- model_name = "/models/Llama-3.2-11B-Vision-Instruct"
+ model_name = get_model_path("meta-llama/Llama-3.2-11B-Vision-Instruct")
model = AutoModelForImageTextToText.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.language_model.layers"], [40])
@@ -135,7 +136,7 @@ class TestAutoRound:
assert not is_pure_text_model(model)
def test_SmolVLM(self):
- model_name = "/models/SmolVLM-Instruct"
+ model_name = get_model_path("HuggingFaceTB/SmolVLM-Instruct")
model = AutoModelForImageTextToText.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.text_model.layers"], [24])
@@ -146,10 +147,10 @@ class TestAutoRound:
@pytest.mark.skipif(
transformers_version >= version.parse("5.0.0"),
- reason="ChatGLMConfig object has no attribute max_length, https://github.com/huggingface/transformers/issues/43881",
+ reason="https://huggingface.co/zai-org/glm-4v-9b/discussions/46",
)
def test_glm_4v(self):
- model_name = "/models/glm-4v-9b"
+ model_name = get_model_path("zai-org/glm-4v-9b")
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["transformer.encoder.layers"], [40])
@@ -161,7 +162,7 @@ class TestAutoRound:
assert not is_pure_text_model(model)
def test_gemma3(self):
- model_name = "/models/gemma-3-12b-it"
+ model_name = get_model_path("google/gemma-3-12b-it")
model = Gemma3ForConditionalGeneration.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.language_model.layers"], [48])
@@ -173,7 +174,7 @@ class TestAutoRound:
assert not is_pure_text_model(model)
def test_Mistral3(self):
- model_name = "/models/Mistral-Small-3.2-24B-Instruct-2506"
+ model_name = get_model_path("mistralai/Mistral-Small-3.2-24B-Instruct-2506")
model = Mistral3ForConditionalGeneration.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.language_model.layers"], [40])
@@ -186,10 +187,10 @@ class TestAutoRound:
@pytest.mark.skipif(
transformers_version >= version.parse("5.0.0"),
- reason="AttributeError: 'MolmoForCausalLM' object has no attribute 'all_tied_weights_keys', https://github.com/huggingface/transformers/issues/43883",
+ reason="https://huggingface.co/allenai/Molmo-7B-D-0924/discussions/51",
)
def test_Molmo(self):
- model_name = "/models/Molmo-7B-D-0924"
+ model_name = get_model_path("allenai/Molmo-7B-D-0924")
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
block_names = get_block_names(model)
self.check_block_names(block_names, ["model.transformer.blocks"], [28])
@@ -200,14 +201,10 @@ class TestAutoRound:
)
assert not is_pure_text_model(model)
- @pytest.mark.skipif(
- transformers_version >= version.parse("5.0.0"),
- reason="cannot import name 'MT5Tokenizer' from 'transformers', https://github.com/huggingface/diffusers/issues/13035",
- )
def test_flux(self):
from diffusers import AutoPipelineForText2Image
- model_name = "/dataset/FLUX.1-dev"
+ model_name = "black-forest-labs/FLUX.1-dev"
pipe = AutoPipelineForText2Image.from_pretrained(model_name)
model = pipe.transformer
diff --git a/test/test_cuda/models/test_mllm.py b/test/test_cuda/models/test_mllm.py
index 13643388c..52d09175c 100644
--- a/test/test_cuda/models/test_mllm.py
+++ b/test/test_cuda/models/test_mllm.py
@@ -36,14 +36,16 @@ class VisionDataLoader:
}
[email protected]_ci(reason="Only tiny model is suggested")
class TestAutoRoundMLLM:
- @classmethod
- def setup_class(self):
- self.save_dir = "./saved"
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
@classmethod
def teardown_class(self):
- shutil.rmtree(self.save_dir, ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
# def test_vision_generation(self):
@@ -110,36 +112,26 @@ class TestAutoRoundMLLM:
@require_gptqmodel
@require_optimum
def test_vlm_tune(self):
- from transformers import AutoProcessor, AutoTokenizer
-
from auto_round import AutoRoundMLLM
## load the model
- model_name = "/models/Qwen2-VL-2B-Instruct"
- model = Qwen2VLForConditionalGeneration.from_pretrained(model_name, trust_remote_code=True, device_map="auto")
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True)
-
+ model_name = get_model_path("Qwen/Qwen2-VL-2B-Instruct")
## quantize the model
bits, group_size, sym = 4, 128, True
- autoround = AutoRoundMLLM(
- model, tokenizer, processor, bits=bits, group_size=group_size, sym=sym, iters=1, nsamples=1
- )
+ autoround = AutoRoundMLLM(model_name, bits=bits, group_size=group_size, sym=sym, iters=1, nsamples=1)
autoround.quantize()
quantized_model_path = self.save_dir
autoround.save_quantized(quantized_model_path, format="auto_round", inplace=False)
self.qwen_inference(quantized_model_path)
- shutil.rmtree(self.save_dir, ignore_errors=True)
autoround.save_quantized(quantized_model_path, format="auto_gptq", inplace=False)
self.qwen_inference(quantized_model_path)
- shutil.rmtree(self.save_dir, ignore_errors=True)
@require_vlm_env
def test_mm_block_name(self):
from auto_round.utils import get_block_names
- model_name = "/models/Llama-3.2-11B-Vision-Instruct/"
+ model_name = get_model_path("meta-llama/Llama-3.2-11B-Vision-Instruct")
from transformers import MllamaForConditionalGeneration
model = MllamaForConditionalGeneration.from_pretrained(model_name, trust_remote_code=True, device_map="auto")
@@ -151,31 +143,31 @@ class TestAutoRoundMLLM:
assert len(block_name) == 1
assert get_block_names(model) == block_name
- def test_mllm_detect(self):
+ @pytest.mark.parametrize(
+ "model_name",
+ [
+ "meta-llama/Llama-3.2-11B-Vision-Instruct",
+ "deepseek-ai/deepseek-vl2-tiny",
+ "google/gemma-3-12b-it",
+ "microsoft/Phi-3.5-vision-instruct",
+ "Qwen/Qwen2-VL-2B-Instruct",
+ "HuggingFaceTB/SmolVLM-256M-Instruct",
+ "mistralai/Mistral-Small-3.2-24B-Instruct-2506",
+ "OpenGVLab/InternVL3-1B",
+ "Qwen/Qwen2.5-1.5B-Instruct",
+ ],
+ )
+ def test_mllm_detect(self, model_name):
from auto_round.utils import is_mllm_model, llm_load_model, mllm_load_model
- for model_name in [
- "/models/Llama-3.2-11B-Vision-Instruct/",
- "/models/deepseek-vl2-tiny/",
- "/models/gemma-3-12b-it/",
- "/models/Phi-3.5-vision-instruct",
- "/models/Qwen2-VL-2B-Instruct",
- "/models/SmolVLM-256M-Instruct",
- "/models/Mistral-Small-3.2-24B-Instruct-2506",
- "/models/InternVL3-1B",
- "/models/pixtral-12b",
- ]:
- assert is_mllm_model(model_name)
- try:
- model, _, _, _ = mllm_load_model(model_name)
- except:
- continue
- assert is_mllm_model(model)
-
- for model_name in ["/models/Qwen2.5-1.5B-Instruct/"]:
+ if model_name == "Qwen/Qwen2.5-1.5B-Instruct":
+ model_name = get_model_path(model_name)
assert not is_mllm_model(model_name)
model, _ = llm_load_model(model_name)
assert not is_mllm_model(model)
+ else:
+ model_name = get_model_path(model_name)
+ assert is_mllm_model(model_name)
def test_llama32_vision_early_stop_tracking(self):
"""Test early-stop during calibration for Llama-3.2-11B-Vision-Instruct."""
diff --git a/test/test_cuda/models/test_moe_model.py b/test/test_cuda/models/test_moe_model.py
index 006dc78e6..95c61bd55 100644
--- a/test/test_cuda/models/test_moe_model.py
+++ b/test/test_cuda/models/test_moe_model.py
@@ -2,7 +2,7 @@ import shutil
import pytest
import torch
-from transformers import AutoConfig, AutoProcessor, AutoTokenizer, Llama4ForConditionalGeneration
+from transformers import AutoTokenizer, Llama4ForConditionalGeneration
from transformers.models.gpt_oss.modeling_gpt_oss import GptOssForCausalLM
from transformers.models.qwen3_vl_moe.modeling_qwen3_vl_moe import Qwen3VLMoeForConditionalGeneration
@@ -11,164 +11,19 @@ from auto_round import AutoRound
from ...helpers import check_version
-def setup_gpt_oss():
- """Fixture to set up the GPT-OSS model and tokenizer."""
- model_name = "openai/gpt-oss-20b"
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
- config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
- config.num_hidden_layers = 1 # Reduce layers for testing
- model = GptOssForCausalLM(config)
- output_dir = "test_quantized_gpt_oss"
- return model, tokenizer, output_dir, config
-
-
-def setup_llama4():
- """Fixture to set up the llama4 model and tokenizer."""
- model_name = "/dataset/Llama-4-Scout-17B-16E-Instruct"
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
- config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
-
- # TODO: Remove after https://github.com/huggingface/transformers/issues/43525 is resolved
- config.pad_token_id = None
-
- config.vision_config.num_hidden_layers = 1 # Reduce layers for testing
- config.text_config.num_hidden_layers = 1
- model = Llama4ForConditionalGeneration(config)
- output_dir = "test_quantized_llama4"
- return model, tokenizer, output_dir, config
-
-
-def setup_qwen3_vl_moe():
- """Fixture to set up the qwen3_vl_moe model and tokenizer."""
- model_name = "/models/Qwen3-VL-30B-A3B-Instruct"
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- config = AutoConfig.from_pretrained(model_name)
-
- # TODO: Remove after https://github.com/huggingface/transformers/pull/43453 is merged
- config.text_config.pad_token_id = None
- # Reduce model depth for faster and cheaper test runs
- config.vision_config.num_hidden_layers = 1
- config.text_config.num_hidden_layers = 1
- config.num_hidden_layers = 1 # Reduce layers for testing
- processor = AutoProcessor.from_pretrained(model_name)
- model = Qwen3VLMoeForConditionalGeneration(config)
- output_dir = "test_quantized_qwen3_vl_moe"
- return model, tokenizer, processor, output_dir, config
-
-
-def quantize_model(model, tokenizer, output_dir, scheme, iters=0, ignore_layers="self_attn,router,lm_head,mlp.gate"):
- """Helper function to quantize the model with the given scheme."""
- autoround = AutoRound(
- model,
- tokenizer,
- scheme=scheme,
- nsamples=2,
- iters=iters,
- seqlen=32,
- ignore_layers=ignore_layers,
- )
- quantized_model, save_folder = autoround.quantize_and_save(format="auto_round", output_dir=output_dir)
- return quantized_model
-
-
-def test_gptoss(setup_gpt_oss):
- model, tokenizer, output_dir, config = setup_gpt_oss
-
- # Below parameter is set to be same as the full model
- # Remove it to avoid mismatch during quantized model loading
- delattr(model.config, "layer_types")
-
- quantized_model = quantize_model(model, tokenizer, output_dir, "MXFP4", ignore_layers="self_attn,lm_head")
-
- # Ensure the quantized model is not None
- assert quantized_model is not None, "Quantized model should not be None."
-
- loaded_model = GptOssForCausalLM.from_pretrained(output_dir)
- quantized_model.to("cuda")
- loaded_model.to("cuda")
- for n, m in quantized_model.named_modules():
- if m.__class__.__name__ == "QuantLinear":
- loaded_m = loaded_model.get_submodule(n)
- assert (loaded_m.weight_packed == m.weight_packed).all()
-
- inp = torch.randint(0, 100, (1, 64)).to("cuda")
- with torch.inference_mode():
- loaded_out = loaded_model(inp)
-
- # clean the output directory after test
- shutil.rmtree(output_dir, ignore_errors=True)
-
-
-def test_llama4(setup_llama4):
- model, tokenizer, output_dir, config = setup_llama4
-
- # Below parameters are set to be same as the full model
- # Remove them to avoid mismatch during quantized model loading
- model.config.text_config.no_rope_layers = []
- delattr(model.config.text_config, "moe_layers")
- delattr(model.config.text_config, "layer_types")
-
- quantized_model = quantize_model(model, tokenizer, output_dir, "MXFP4", ignore_layers="self_attn,router,lm_head")
-
- # Ensure the quantized model is not None
- assert quantized_model is not None, "Quantized model should not be None."
-
- loaded_model = Llama4ForConditionalGeneration.from_pretrained(output_dir)
- quantized_model.to("cuda")
- loaded_model.to("cuda")
- for n, m in quantized_model.named_modules():
- if m.__class__.__name__ == "QuantLinear":
- loaded_m = loaded_model.get_submodule(n)
- assert (loaded_m.weight_packed == m.weight_packed).all()
-
- inp = torch.randint(0, 100, (1, 64)).to("cuda")
- with torch.inference_mode():
- loaded_out = loaded_model(inp)
-
- # clean the output directory after test
- shutil.rmtree(output_dir, ignore_errors=True)
-
-
-def setup_qwen35_moe():
- """Fixture to set up the Qwen3.5 MoE model, tokenizer, and processor."""
[email protected](not check_version("transformers>=5.2.0"), reason="requires transformers >= 5.2.0")
+def test_qwen3_5_moe(tiny_qwen35_moe_model_path):
from transformers import Qwen3_5MoeForConditionalGeneration
- model_name = "/models/Qwen3.5-35B-A3B"
- tokenizer = AutoTokenizer.from_pretrained(model_name)
- config = AutoConfig.from_pretrained(model_name)
- config.text_config.pad_token_id = None
- config.vision_config.num_hidden_layers = 1
- config.text_config.num_hidden_layers = 4
- config.num_hidden_layers = 1 # Reduce layers for testing
- config.text_config.layer_types = config.text_config.layer_types[
- : config.text_config.num_hidden_layers
- ] # Reduce layers for testing
- config.text_config.use_cache = False
- processor = AutoProcessor.from_pretrained(model_name)
- model = Qwen3_5MoeForConditionalGeneration(config)
- # model = Qwen3_5MoeForConditionalGeneration.from_pretrained(model_name)
output_dir = "test_quantized_qwen35_moe"
- return model, tokenizer, processor, output_dir, config
-
-
[email protected](not check_version("transformers>=5.2.0"), reason="requires transformers >= 5.2.0")
-def test_qwen3_5_moe(setup_qwen35_moe):
- model, tokenizer, processor, output_dir, config = setup_qwen35_moe
ar = AutoRound(
- model,
- tokenizer=tokenizer,
- processor=processor,
+ tiny_qwen35_moe_model_path,
nsamples=2,
seqlen=32,
iters=1,
)
quantized_model, _ = ar.quantize_and_save(format="auto_round", output_dir=output_dir)
assert quantized_model is not None, "Quantized model should not be None."
- from transformers import Qwen3_5MoeForConditionalGeneration
loaded_model = Qwen3_5MoeForConditionalGeneration.from_pretrained(output_dir)
loaded_model.to("cuda")
@@ -178,40 +33,3 @@ def test_qwen3_5_moe(setup_qwen35_moe):
loaded_out = loaded_model(inp)
shutil.rmtree(output_dir, ignore_errors=True)
-
-
-# using general recipe when transformers >= 5.0.0
-def test_qwen3_vl_moe_mxfp(setup_qwen3_vl_moe):
- model, tokenizer, processor, output_dir, config = setup_qwen3_vl_moe
- autoround = AutoRound(
- model,
- tokenizer=tokenizer,
- processor=processor,
- scheme="MXFP4",
- nsamples=2,
- seqlen=32,
- iters=1,
- ignore_layers="self_attn,lm_head,mlp.gate",
- )
- quantized_model, _ = autoround.quantize_and_save(format="auto_round", output_dir=output_dir)
- assert quantized_model is not None, "Quantized model should not be None."
- loaded_model = Qwen3VLMoeForConditionalGeneration.from_pretrained(output_dir)
- loaded_model.to("cuda")
- quantized_model.to("cuda")
- for n, m in quantized_model.named_modules():
- if m.__class__.__name__ == "QuantLinear":
- loaded_m = loaded_model.get_submodule(n)
- assert (loaded_m.weight_packed == m.weight_packed).all()
-
- inp = torch.randint(0, 100, (1, 64)).to("cuda")
- with torch.inference_mode():
- loaded_out = loaded_model(inp)
-
- # test generation
- tokenizer = AutoTokenizer.from_pretrained(output_dir)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(device=loaded_model.device)
- print(tokenizer.decode(loaded_model.generate(**inputs, max_new_tokens=50)[0]))
- # clean the output directory after test
- shutil.rmtree(output_dir, ignore_errors=True)
- loaded_model.to("cuda")
diff --git a/test/test_cuda/models/test_support_vlms.py b/test/test_cuda/models/test_support_vlms.py
index b4ffd2284..e927a3d64 100644
--- a/test/test_cuda/models/test_support_vlms.py
+++ b/test/test_cuda/models/test_support_vlms.py
@@ -4,17 +4,19 @@ import sys
import pytest
import requests
+from huggingface_hub import snapshot_download
from packaging import version
from PIL import Image
from transformers import AutoRoundConfig # # must import for auto-round format
from ...envs import require_gptqmodel, require_package_version_ut, require_vlm_env
-from ...helpers import transformers_version
+from ...helpers import get_model_path, transformers_version
AUTO_ROUND_PATH = __file__.split("/")
AUTO_ROUND_PATH = "/".join(AUTO_ROUND_PATH[: AUTO_ROUND_PATH.index("test")])
[email protected]_ci(reason="Only tiny model is suggested")
class TestSupportVLMS:
@classmethod
@@ -29,7 +31,7 @@ class TestSupportVLMS:
@require_gptqmodel
def test_qwen2(self):
- model_path = "/models/Qwen2-VL-2B-Instruct/"
+ model_path = get_model_path("Qwen/Qwen2-VL-2B-Instruct")
# test tune
res = os.system(
f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {self.python_path} -m auto_round --mllm "
@@ -84,7 +86,7 @@ class TestSupportVLMS:
@require_vlm_env
@require_package_version_ut("transformers", "<4.54.0")
def test_phi3(self):
- model_path = "/models/Phi-3.5-vision-instruct/"
+ model_path = get_model_path("microsoft/Phi-3.5-vision-instruct")
## test tune
res = os.system(
f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {self.python_path} -m auto_round --mllm "
@@ -96,7 +98,10 @@ class TestSupportVLMS:
from transformers import AutoModelForCausalLM, AutoProcessor
quantized_model_path = os.path.join(self.save_dir, "Phi-3.5-vision-instruct-w4g128")
- res = os.system(f"cp /models/Phi-3.5-vision-instruct/*.py {quantized_model_path}")
+ local_model_path = (
+ model_path if os.path.isdir(model_path) else snapshot_download(model_path, allow_patterns=["*.py"])
+ )
+ res = os.system(f"cp {local_model_path}/*.py {quantized_model_path}")
model = AutoModelForCausalLM.from_pretrained(
quantized_model_path,
device_map=f"cuda:{self.device}",
@@ -131,7 +136,7 @@ class TestSupportVLMS:
@require_vlm_env
def test_phi3_vision_awq(self):
- model_path = "/models/Phi-3.5-vision-instruct/"
+ model_path = get_model_path("microsoft/Phi-3.5-vision-instruct")
## test tune
res = os.system(
f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {self.python_path} -m auto_round --mllm "
@@ -145,7 +150,10 @@ class TestSupportVLMS:
from transformers import AutoModelForCausalLM, AutoProcessor
quantized_model_path = os.path.join(self.save_dir, "Phi-3.5-vision-instruct-w4g128")
- res = os.system(f"cp /models/Phi-3.5-vision-instruct/*.py {quantized_model_path}")
+ local_model_path = (
+ model_path if os.path.isdir(model_path) else snapshot_download(model_path, allow_patterns=["*.py"])
+ )
+ res = os.system(f"cp {local_model_path}/*.py {quantized_model_path}")
model = AutoModelForCausalLM.from_pretrained(
quantized_model_path, device_map=f"cuda:{self.device}", trust_remote_code=True, torch_dtype="auto"
)
@@ -183,7 +191,7 @@ class TestSupportVLMS:
reason="transformers api changed",
)
def test_glm(self):
- model_path = "/models/glm-4v-9b/"
+ model_path = get_model_path("THUDM/glm-4v-9b")
## test tune
res = os.system(
f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {self.python_path} -m auto_round "
@@ -192,7 +200,7 @@ class TestSupportVLMS:
assert not (res > 0 or res == -1), "glm-4v-9b tuning fail"
def test_granite_vision(self):
- model_path = "/models/granite-vision-3.2-2b"
+ model_path = get_model_path("ibm-granite/granite-vision-3.2-2b")
## test tune
res = os.system(
f"PYTHONPATH='{AUTO_ROUND_PATH}:$PYTHONPATH' {self.python_path} -m auto_round "
diff --git a/test/test_cuda/quantization/test_2_3bits.py b/test/test_cuda/quantization/test_2_3bits.py
deleted file mode 100644
index 90637d03f..000000000
--- a/test/test_cuda/quantization/test_2_3bits.py
+++ /dev/null
@@ -1,81 +0,0 @@
-import copy
-import shutil
-
-import pytest
-import torch
-import transformers
-from lm_eval.utils import make_table # pylint: disable=E0401
-from transformers import AutoModelForCausalLM, AutoRoundConfig, AutoTokenizer
-
-from auto_round import AutoRound
-
-from ...envs import require_autogptq, require_greater_than_050, require_greater_than_051
-from ...helpers import evaluate_accuracy, get_model_path, model_infer
-
-
-class TestAutoRound:
- save_dir = "./saved"
-
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
- yield
-
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- @require_greater_than_051
- def test_3bits_autoround(self):
- model_name = get_model_path("facebook/opt-125m")
- autoround = AutoRound(model_name, bits=3)
- quantized_model_path = self.save_dir
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round") ##will convert to gptq model
-
- quantization_config = AutoRoundConfig(backend="torch")
- model = AutoModelForCausalLM.from_pretrained(
- quantized_model_path, torch_dtype=torch.float16, device_map="auto", quantization_config=quantization_config
- )
-
- tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- model_infer(model, tokenizer)
- evaluate_accuracy(model, tokenizer, threshold=0.3, batch_size=16)
-
- @require_greater_than_051
- def test_3bits_asym_autoround(self):
- model_name = get_model_path("facebook/opt-125m")
- bits, sym = 3, False
- autoround = AutoRound(model_name, bits=bits, sym=sym)
- autoround.quantize_and_save(self.save_dir, format="auto_round", inplace=False)
- evaluate_accuracy(self.save_dir, threshold=0.32, batch_size="auto")
- shutil.rmtree("./saved", ignore_errors=True)
-
- @require_greater_than_050
- def test_norm_bias_tuning(self):
- model_name = get_model_path("facebook/opt-125m")
- autoround = AutoRound(model_name, bits=2, group_size=64, enable_norm_bias_tuning=True)
- autoround.quantize()
-
- ##test auto_round format
- autoround.save_quantized(self.save_dir, format="auto_round", inplace=False)
- evaluate_accuracy(self.save_dir, threshold=0.18, batch_size="auto")
- shutil.rmtree("./saved", ignore_errors=True)
-
- @require_greater_than_050
- def test_2bits_autoround(self):
- model_name = get_model_path("facebook/opt-125m")
- autoround = AutoRound(model_name, bits=2, group_size=64)
- autoround.quantize()
-
- ##test auto_round format
- autoround.save_quantized(self.save_dir, format="auto_round", inplace=False)
- evaluate_accuracy(self.save_dir, threshold=0.17, batch_size="auto")
- shutil.rmtree("./saved", ignore_errors=True)
-
- autoround.save_quantized(self.save_dir, format="auto_gptq", inplace=False)
- evaluate_accuracy(self.save_dir, threshold=0.17, batch_size="auto")
- shutil.rmtree("./saved", ignore_errors=True)
diff --git a/test/test_cuda/quantization/test_asym.py b/test/test_cuda/quantization/test_asym.py
index 846ccac34..5145cf13d 100644
--- a/test/test_cuda/quantization/test_asym.py
+++ b/test/test_cuda/quantization/test_asym.py
@@ -9,148 +9,69 @@ from transformers import AutoModelForCausalLM, AutoRoundConfig, AutoTokenizer
from auto_round import AutoRound
-
-class LLMDataLoader:
- def __init__(self):
- self.batch_size = 1
-
- def __iter__(self):
- for i in range(3):
- yield torch.ones([1, 10], dtype=torch.long)
+from ...helpers import get_model_path, model_infer
class TestAutoRoundAsym:
- save_dir = "./saved"
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
@pytest.fixture(autouse=True, scope="class")
def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
yield
-
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
- def test_asym_group_size(self, tiny_opt_model_path):
- for group_size in [32, 64, 128]:
- bits, sym = 4, False
- ar = AutoRound(
- tiny_opt_model_path, bits=bits, group_size=group_size, sym=sym, iters=0, seqlen=2, nsamples=1
- )
- ar.quantize_and_save(format="auto_round", output_dir=self.save_dir)
-
- # TODO when ark is ready, uncomment the following lines to do inference test
-
- # model = AutoModelForCausalLM.from_pretrained(
- # self.save_dir,
- # torch_dtype="auto",
- # device_map="auto",
- # )
-
- # tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- # model_infer(model, tokenizer)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- def test_asym_bits(self, tiny_opt_model_path):
- for bits in [2, 3, 8]:
- group_size, sym = 128, False
- ar = AutoRound(
- tiny_opt_model_path, bits=bits, group_size=group_size, sym=sym, iters=0, seqlen=2, nsamples=1
- )
- ar.quantize_and_save(format="auto_round", output_dir=self.save_dir)
-
- # TODO when ark is ready, uncomment the following lines to do inference test
-
- # model = AutoModelForCausalLM.from_pretrained(
- # self.save_dir,
- # torch_dtype="auto",
- # device_map="auto",
- # )
-
- # tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- # model_infer(model, tokenizer)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- # use parameters later
- def test_asym_format(self, tiny_opt_model_path):
- for format in ["auto_round", "auto_round:auto_gptq", "auto_round:gptqmodel"]:
- bits, group_size, sym = 4, 128, False
- ar = AutoRound(
- tiny_opt_model_path, bits=bits, group_size=group_size, sym=sym, iters=0, seqlen=2, nsamples=1
- )
- # TODO when ark is ready, uncomment the following lines to do inference test
- ar.quantize_and_save(format=format, output_dir=self.save_dir)
-
- # model = AutoModelForCausalLM.from_pretrained(
- # self.save_dir,
- # torch_dtype="auto",
- # device_map="auto",
- # )
-
- # tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- # model_infer(model, tokenizer)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- def test_asym_group_size_with_tuning(self, tiny_opt_model_path):
- for group_size in [32, 64, 128]:
- bits, sym = 4, False
- ar = AutoRound(
- tiny_opt_model_path, bits=bits, group_size=group_size, sym=sym, iters=1, seqlen=2, nsamples=1
- )
- ar.quantize_and_save(format="auto_round", output_dir=self.save_dir)
-
- # TODO when ark is ready, uncomment the following lines to do inference test
-
- # model = AutoModelForCausalLM.from_pretrained(
- # self.save_dir,
- # torch_dtype="auto",
- # device_map="auto",
- # )
-
- # tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- # model_infer(model, tokenizer)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- def test_asym_bits_with_tuning(self, tiny_opt_model_path):
- for bits in [2, 3, 8]:
- group_size, sym = 128, False
- ar = AutoRound(
- tiny_opt_model_path, bits=bits, group_size=group_size, sym=sym, iters=1, seqlen=2, nsamples=1
- )
- ar.quantize_and_save(format="auto_round", output_dir=self.save_dir)
-
- # TODO when ark is ready, uncomment the following lines to do inference test
-
- # model = AutoModelForCausalLM.from_pretrained(
- # self.save_dir,
- # torch_dtype="auto",
- # device_map="auto",
- # )
-
- # tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- # model_infer(model, tokenizer)
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- # use parameters later
- def test_asym_format_with_tuning(self, tiny_opt_model_path):
- for format in ["auto_round", "auto_round:auto_gptq", "auto_round:gptqmodel"]:
- bits, group_size, sym = 4, 128, False
- ar = AutoRound(
- tiny_opt_model_path, bits=bits, group_size=group_size, sym=sym, iters=1, seqlen=2, nsamples=1
- )
- # TODO when ark is ready, uncomment the following lines to do inference test
- ar.quantize_and_save(format=format, output_dir=self.save_dir)
-
- # model = AutoModelForCausalLM.from_pretrained(
- # self.save_dir,
- # torch_dtype="auto",
- # device_map="auto",
- # )
-
- # tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- # model_infer(model, tokenizer)
- shutil.rmtree(self.save_dir, ignore_errors=True)
+ @pytest.mark.parametrize("group_size", [32, 64, 128])
+ def test_asym_group_size_with_tuning(self, group_size, tiny_opt_model_path):
+ bits, sym = 4, False
+ ar = AutoRound(tiny_opt_model_path, bits=bits, group_size=group_size, sym=sym, iters=1, seqlen=2, nsamples=1)
+ ar.quantize_and_save(format="auto_round", output_dir=self.save_dir)
+
+ model = AutoModelForCausalLM.from_pretrained(
+ self.save_dir,
+ torch_dtype="auto",
+ device_map="auto",
+ )
+
+ tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
+ model_infer(model, tokenizer)
+
+ @pytest.mark.skip_ci(reason="Not necessary since it's covered by backend tests") # skip this test in CI
+ @pytest.mark.parametrize("bits", [2, 3, 8])
+ def test_asym_bits_with_tuning(self, bits, tiny_opt_model_path):
+ group_size, sym = 128, False
+ ar = AutoRound(tiny_opt_model_path, bits=bits, group_size=group_size, sym=sym, iters=1, seqlen=2, nsamples=1)
+ ar.quantize_and_save(format="auto_round", output_dir=self.save_dir)
+
+ model = AutoModelForCausalLM.from_pretrained(
+ self.save_dir,
+ torch_dtype="auto",
+ device_map="auto",
+ )
+
+ tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
+ model_infer(model, tokenizer)
+
+ @pytest.mark.skip_ci(reason="Not necessary since it's covered by backend tests") # skip this test in CI
+ @pytest.mark.parametrize("format", ["auto_round", "auto_round:auto_gptq", "auto_round:gptqmodel"])
+ def test_asym_format_with_tuning(self, format, tiny_opt_model_path):
+ bits, group_size, sym = 4, 128, False
+ ar = AutoRound(tiny_opt_model_path, bits=bits, group_size=group_size, sym=sym, iters=1, seqlen=2, nsamples=1)
+ ar.quantize_and_save(format=format, output_dir=self.save_dir)
+
+ if format == "auto_round:auto_gptq":
+ # Cannot load correctly, skip auto_gptq since it's deprecated.
+ return
+
+ model = AutoModelForCausalLM.from_pretrained(
+ self.save_dir,
+ torch_dtype="auto",
+ device_map="auto",
+ )
+
+ tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
+ model_infer(model, tokenizer)
diff --git a/test/test_cuda/quantization/test_block_fp.py b/test/test_cuda/quantization/test_block_fp.py
deleted file mode 100644
index 6ee0ababb..000000000
--- a/test/test_cuda/quantization/test_block_fp.py
+++ /dev/null
@@ -1,64 +0,0 @@
-import shutil
-from math import ceil
-
-import pytest
-import torch
-
-from auto_round import AutoRound
-from auto_round.data_type.fp8 import quant_block_fp_sym
-from auto_round.data_type.utils import reshape_pad_tensor_by_group_size, revert_tensor_by_pad
-
-from ...helpers import evaluate_accuracy, get_model_path
-
-
-class TestAutoRoundBlockFP:
- @classmethod
- def setup_class(self):
- self.model_name = get_model_path("Qwen/Qwen2.5-1.5B-Instruct")
- self.save_dir = "./saved"
-
- @classmethod
- def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- def test_fp8_block_fp8_format(self):
- model_name = self.model_name
-
- scheme = "FP8_BLOCK"
- autoround = AutoRound(
- model_name,
- scheme=scheme,
- iters=2,
- seqlen=2,
- )
- quantized_model_path = self.save_dir
- compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="fp8")
- tmp_layer = compressed_model.model.layers[1].self_attn.q_proj
- assert hasattr(tmp_layer, "weight_scale_inv")
- assert tmp_layer.weight.dtype is torch.float8_e4m3fn
- assert list(tmp_layer.weight_scale_inv.shape) == [12, 12]
- assert compressed_model.config.quantization_config["quant_method"] == "fp8"
- assert compressed_model.config.quantization_config["weight_block_size"] == (128, 128)
- evaluate_accuracy(quantized_model_path, threshold=0.55, batch_size=32, limit=100)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- def test_fp8_block_llm_compressor_format(self):
- model_name = self.model_name
-
- scheme = "FP8_BLOCK"
- autoround = AutoRound(
- model_name,
- scheme=scheme,
- iters=2,
- seqlen=2,
- )
- quantized_model_path = self.save_dir
- compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="llm_compressor")
- tmp_layer = compressed_model.model.layers[1].self_attn.q_proj
- assert hasattr(tmp_layer, "weight_scale")
- assert tmp_layer.weight.dtype is torch.float8_e4m3fn
- assert list(tmp_layer.weight_scale.shape) == [12, 12]
- assert compressed_model.config.quantization_config["quant_method"] == "compressed-tensors"
- evaluate_accuracy(quantized_model_path, threshold=0.55, batch_size=32, limit=100)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
diff --git a/test/test_cuda/quantization/test_mix_bits.py b/test/test_cuda/quantization/test_mix_bits.py
deleted file mode 100644
index 68180c5b8..000000000
--- a/test/test_cuda/quantization/test_mix_bits.py
+++ /dev/null
@@ -1,319 +0,0 @@
-import json
-import os
-import shutil
-from pathlib import Path
-
-import pytest
-import torch
-from transformers import AutoModelForCausalLM, AutoRoundConfig, AutoTokenizer
-
-from auto_round import AutoRound
-
-from ...envs import (
- require_gptqmodel,
-)
-from ...helpers import get_model_path
-
-
-class TestAutoRound:
- save_dir = "./saved"
-
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
- yield
-
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- @require_gptqmodel
- def test_mixed_gptqmodel(self, tiny_opt_model_path, dataloader):
- scheme = "W4A16"
- layer_config = {
- "k_proj": {"bits": 8}, # part name
- "lm_head": {"bits": 4}, # set lm_head quant
- "fc1": {"bits": 16},
- "model.decoder.layers.0.self_attn.v_proj": {"bits": 16},
- "model.decoder.layers.0.self_attn.q_proj": {"bits": 8}, # full name
- }
- autoround = AutoRound(
- model=tiny_opt_model_path,
- scheme=scheme,
- iters=2,
- seqlen=2,
- layer_config=layer_config,
- dataset=dataloader,
- )
- quantized_model_path = self.save_dir
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_gptq")
- from gptqmodel import GPTQModel
-
- model = GPTQModel.load(quantized_model_path)
- assert model.model.model.decoder.layers[0].self_attn.k_proj.bits == 8
- assert model.model.model.decoder.layers[0].self_attn.q_proj.bits == 8
- assert model.model.model.decoder.layers[1].self_attn.v_proj.bits == 4
- res = model.tokenizer.decode(model.generate("Uncovering deep insights begins with")[0])
- print(res)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- def test_mixed_gptqmodel_convert_to_ar(self, tiny_opt_model_path, dataloader):
- layer_config = {
- "k_proj": {"bits": 8}, # part name
- "lm_head": {"bits": 4}, # set lm_head quant
- "model.decoder.layers.0.self_attn.v_proj": {"bits": 16},
- "model.decoder.layers.0.self_attn.q_proj": {"bits": 8}, # full name
- }
- autoround = AutoRound(
- model=tiny_opt_model_path,
- scheme="W4A16",
- iters=2,
- seqlen=2,
- layer_config=layer_config,
- dataset=dataloader,
- )
- quantized_model_path = self.save_dir
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_gptq")
- quantization_config = AutoRoundConfig()
- model = AutoModelForCausalLM.from_pretrained(
- quantized_model_path, device_map="auto", quantization_config=quantization_config
- )
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=5)[0])
- print(res)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- def test_mixed_autoround_format(self, tiny_opt_model_path, dataloader):
- layer_config = {
- "k_proj": {"bits": 8},
- "q_proj": {"bits": 3},
- "lm_head": {"bits": 16},
- "fc1": {"bits": 16},
- }
- autoround = AutoRound(
- model=tiny_opt_model_path,
- scheme="W4A16",
- iters=2,
- seqlen=2,
- dataset=dataloader,
- layer_config=layer_config,
- )
- quantized_model_path = "self.save_dir"
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
- config_file = Path(quantized_model_path) / "config.json"
- with open(config_file, "r", encoding="utf-8") as f:
- config = json.load(f)
- quant_config = config.get("quantization_config", {})
- extra_config = quant_config.get("extra_config", {})
- # check extra_config only saved attributes differing from Scheme values
- assert "act_bits" not in extra_config[".*fc1.*"].keys() ## TODO refine this assert
- assert "group_size" not in extra_config[".*fc1.*"].keys()
- assert "act_bits" not in extra_config["model.decoder.layers.0.self_attn.k_proj"].keys()
- assert "group_size" not in extra_config["model.decoder.layers.0.self_attn.k_proj"].keys()
- assert "group_size" not in extra_config["model.decoder.layers.1.self_attn.q_proj"].keys()
- assert "bits" in extra_config["model.decoder.layers.1.self_attn.q_proj"].keys()
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
- assert model.model.decoder.layers[0].self_attn.k_proj.bits == 8
- assert model.model.decoder.layers[0].self_attn.q_proj.bits == 3
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- @require_gptqmodel
- def test_fallback_regex_for_awq_format(self, tiny_opt_model_path, dataloader):
- layer_config = {
- "lm_head": {"bits": 16},
- "fc1": {"bits": 16},
- }
- autoround = AutoRound(
- model=tiny_opt_model_path,
- scheme="W4A16",
- iters=2,
- seqlen=2,
- dataset=dataloader,
- layer_config=layer_config,
- )
- quantized_model_path = "self.save_dir"
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_awq")
- quantization_config = AutoRoundConfig()
- model = AutoModelForCausalLM.from_pretrained(
- quantized_model_path, device_map="auto", quantization_config=quantization_config
- )
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- def test_mixed_ar_format_part_name_hf_loading(self, tiny_opt_model_path, dataloader):
- layer_config = {
- "k_proj": {"bits": 8}, # part name
- "lm_head": {"bits": 16}, # full name
- ".*fc1.*": {"bits": 16}, # standard regex
- }
- autoround = AutoRound(
- model=tiny_opt_model_path,
- scheme="W4A16",
- iters=2,
- seqlen=2,
- dataset=dataloader,
- layer_config=layer_config,
- )
- quantized_model_path = "self.save_dir"
- autoround.quantize()
- autoround.save_quantized(output_dir=quantized_model_path, format="auto_round")
- # remove old extra_config(which contains full name layer configs), only test regex config loading
- new_extra_config = {
- ".*fc1.*": { # standard regex
- "bits": 16,
- },
- "k_proj": { # part name
- "bits": 8,
- },
- }
- config_file = Path(quantized_model_path) / "config.json"
- with open(config_file, "r", encoding="utf-8") as f:
- config = json.load(f)
- quant_config = config.get("quantization_config", {})
- old_extra_config = quant_config.get("extra_config", {})
- # check extra_config only saved attributes differing from Scheme values
- assert "sym" not in old_extra_config[".*fc1.*"].keys()
- assert "act_dynamic" not in old_extra_config[".*fc1.*"].keys()
- assert "group_size" not in old_extra_config[".*fc1.*"].keys()
- quant_config["extra_config"] = new_extra_config
- config["quantization_config"] = quant_config
- with open(config_file, "w", encoding="utf-8") as f:
- json.dump(config, f, indent=2, ensure_ascii=False)
-
- model = AutoModelForCausalLM.from_pretrained(quantized_model_path, device_map="auto")
- assert model.model.decoder.layers[0].self_attn.k_proj.bits == 8
- assert model.model.decoder.layers[0].self_attn.q_proj.bits == 4
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- def test_mixed_MXFP_autoround_format_loading(self, dataloader):
- layer_config = {
- "k_proj": {"bits": 8, "act_bits": 8},
- "lm_head": {"bits": 16, "act_bits": 16},
- "fc1": {"bits": 8, "act_bits": 8},
- }
- model_path = get_model_path("facebook/opt-125m")
- autoround = AutoRound(
- model_path,
- scheme="MXFP4",
- iters=2,
- seqlen=2,
- dataset=dataloader,
- layer_config=layer_config,
- )
- quantized_model_path = self.save_dir
- autoround.quantize_and_save(output_dir=quantized_model_path, inplace=False, format="auto_round")
- model = AutoModelForCausalLM.from_pretrained(
- quantized_model_path,
- torch_dtype="auto",
- device_map="auto",
- )
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- from ...helpers import evaluate_accuracy
-
- evaluate_accuracy(model, tokenizer, threshold=0.32, batch_size=16)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- def test_mixed_autoround_format_vllm(self, tiny_opt_model_path, dataloader):
- layer_config = {
- "self_attn": {"bits": 8},
- "lm_head": {"bits": 16},
- }
- autoround = AutoRound(
- tiny_opt_model_path,
- scheme="W4A16",
- iters=2,
- seqlen=2,
- dataset=dataloader,
- layer_config=layer_config,
- )
- autoround.quantize()
- quantized_model_path = self.save_dir
- autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round")
-
- from vllm import LLM, SamplingParams
-
- # Sample prompts.
- prompts = [
- "The capital of France is",
- "The future of AI is",
- ]
- # Create a sampling params object.
- sampling_params = SamplingParams(temperature=0.8, top_p=0.95)
- # Create an LLM.
- QUANTIZATION = "auto-round" # quantized_model_path
- llm = LLM(
- model=quantized_model_path,
- quantization=QUANTIZATION,
- trust_remote_code=True,
- tensor_parallel_size=1,
- allow_deprecated_quantization=True,
- )
- outputs = llm.generate(prompts, sampling_params)
- # Print the outputs.
- for output in outputs:
- prompt = output.prompt
- generated_text = output.outputs[0].text
- # if "France" in prompt:
- assert "!!!" not in generated_text
- print(f"{prompt}: {generated_text}")
- shutil.rmtree(quantized_model_path, ignore_errors=True)
-
- def test_mixed_llmcompressor_format_vllm(self, tiny_opt_model_path, dataloader):
- layer_config = {
- "self_attn": {"bits": 16, "act_bits": 16},
- "lm_head": {"bits": 16, "act_bits": 16},
- "fc1": {"bits": 16, "act_bits": 16},
- }
- autoround = AutoRound(
- tiny_opt_model_path,
- scheme="NVFP4",
- iters=2,
- seqlen=2,
- dataset=dataloader,
- layer_config=layer_config,
- )
- quantized_model_path = self.save_dir
- compressed, _ = autoround.quantize_and_save(
- output_dir=quantized_model_path, inplace=False, format="llm_compressor"
- )
- from vllm import LLM, SamplingParams
-
- # Sample prompts.
- prompts = [
- "The capital of France is",
- "The future of AI is",
- ]
- # Create a sampling params object.
- sampling_params = SamplingParams(temperature=0.8, top_p=0.95)
- # Create an LLM.
- llm = LLM(
- model=quantized_model_path,
- trust_remote_code=True,
- tensor_parallel_size=1,
- allow_deprecated_quantization=True,
- )
- outputs = llm.generate(prompts, sampling_params)
- # Print the outputs.
- for output in outputs:
- prompt = output.prompt
- generated_text = output.outputs[0].text
- print(f"{prompt}: {generated_text}")
- assert "!!!" not in generated_text
- shutil.rmtree(quantized_model_path, ignore_errors=True)
diff --git a/test/test_cuda/quantization/test_mxfp_and_nvfp_quant.py b/test/test_cuda/quantization/test_mxfp_and_nvfp_quant.py
deleted file mode 100644
index c3f3e09c7..000000000
--- a/test/test_cuda/quantization/test_mxfp_and_nvfp_quant.py
+++ /dev/null
@@ -1,81 +0,0 @@
-import shutil
-import tempfile
-
-import pytest
-import torch
-from transformers import AutoModelForCausalLM, AutoTokenizer
-
-from auto_round import AutoRound
-from auto_round import schemes as ar_schemes
-from auto_round.experimental import qmodules as ar_qmodules
-from auto_round.export.export_to_autoround import qlinear_fp as ar_qlinear_fp
-from auto_round.formats import AutoRoundExportFormat
-
-from ...envs import has_module
-from ...helpers import get_model_path
-
-testing_schemes = [
- AutoRoundExportFormat.MXFP8.value,
- AutoRoundExportFormat.MXFP4.value,
- AutoRoundExportFormat.NVFP4.value,
-]
-QMODULE_MAPPING = {
- AutoRoundExportFormat.MXFP8.value: ar_qmodules.MXFP8QuantLinear,
- AutoRoundExportFormat.MXFP4.value: ar_qmodules.MXFP4QuantLinear,
- AutoRoundExportFormat.NVFP4.value: ar_qmodules.NVFP4QuantLinear,
-}
-
-
[email protected]("scheme", testing_schemes)
-def test_e2e_quant_and_infer(scheme, tiny_qwen_model_path):
- # Use a temporary directory for saving the quantized model
- with tempfile.TemporaryDirectory() as temp_dir:
-
- # Load the tokenizer and model
- tokenizer = AutoTokenizer.from_pretrained(tiny_qwen_model_path, trust_remote_code=True)
- model = AutoModelForCausalLM.from_pretrained(
- tiny_qwen_model_path,
- device_map="cpu",
- torch_dtype="auto",
- trust_remote_code=True,
- )
-
- # Initialize AutoRound for quantization
- autoround = AutoRound(
- model,
- tokenizer,
- scheme=scheme,
- iters=0,
- nsamples=2,
- )
-
- # Quantize and save the model to the temporary directory
- quantized_model_path = f"{temp_dir}/tmp_autoround_{scheme}"
- autoround.quantize_and_save(format="auto_round", output_dir=quantized_model_path)
-
- # Perform inference with the quantized model
- model = AutoModelForCausalLM.from_pretrained(
- quantized_model_path,
- torch_dtype="auto",
- )
- model.eval()
- assert has_module(model, QMODULE_MAPPING[scheme]), f"Expected {QMODULE_MAPPING[scheme].__name__} in the model."
-
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- prompt = "Ai is "
-
- # Tokenize the input prompt
- encode = tokenizer.encode(prompt, return_tensors="pt")
-
- # Generate output tokens
- output_tokens = model.generate(
- encode,
- max_length=30,
- )
- output = tokenizer.decode(output_tokens[0], skip_special_tokens=True)
-
- # Print and validate the output
- print(f"Prompt: {prompt}")
- print(f"Output: {output}")
- assert output is not None, "Output should not be None"
diff --git a/test/test_cuda/quantization/test_mxfp_nvfp.py b/test/test_cuda/quantization/test_mxfp_nvfp.py
index f8258c706..3e40e7288 100644
--- a/test/test_cuda/quantization/test_mxfp_nvfp.py
+++ b/test/test_cuda/quantization/test_mxfp_nvfp.py
@@ -1,5 +1,6 @@
import copy
import shutil
+import tempfile
import pytest
import torch
@@ -7,106 +8,88 @@ import transformers
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
from auto_round import AutoRound
+from auto_round import schemes as ar_schemes
+from auto_round.experimental import qmodules as ar_qmodules
+from auto_round.export.export_to_autoround import qlinear_fp as ar_qlinear_fp
+from auto_round.formats import AutoRoundExportFormat
-from ...envs import require_awq, require_optimum
+from ...envs import has_module, require_awq, require_optimum
from ...helpers import get_model_path, save_tiny_model
+testing_schemes = [
+ AutoRoundExportFormat.MXFP8.value,
+ AutoRoundExportFormat.MXFP4.value,
+ AutoRoundExportFormat.NVFP4.value,
+]
+QMODULE_MAPPING = {
+ AutoRoundExportFormat.MXFP8.value: ar_qmodules.MXFP8QuantLinear,
+ AutoRoundExportFormat.MXFP4.value: ar_qmodules.MXFP4QuantLinear,
+ AutoRoundExportFormat.NVFP4.value: ar_qmodules.NVFP4QuantLinear,
+}
-class TestAutoRound:
- save_dir = "./saved"
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
- yield
[email protected]("scheme", testing_schemes)
+def test_e2e_quant_and_infer(scheme, tiny_qwen_model_path):
+ # Use a temporary directory for saving the quantized model
+ with tempfile.TemporaryDirectory() as temp_dir:
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- def test_fp8input_mxfp4_llmcompressor_format(self, dataloader, mock_fp8_capable_device):
- model_name = get_model_path("qwen/Qwen3-0.6B-FP8")
- tiny_model_path = "./tmp/tiny_qwen3_fp8"
- save_tiny_model(model_name, tiny_model_path)
- scheme = "mxfp4"
- ar = AutoRound(
- model=tiny_model_path,
- iters=0,
- seqlen=2,
- scheme=scheme,
- dataset=dataloader,
+ # Load the tokenizer and model
+ tokenizer = AutoTokenizer.from_pretrained(tiny_qwen_model_path, trust_remote_code=True)
+ model = AutoModelForCausalLM.from_pretrained(
+ tiny_qwen_model_path,
+ device_map="cpu",
+ torch_dtype="auto",
+ trust_remote_code=True,
)
- print(ar.model)
- compressed_model, _ = ar.quantize_and_save(output_dir=self.save_dir, format="llm_compressor")
- tmp_layer = compressed_model.model.layers[1].self_attn.q_proj
- assert (
- hasattr(tmp_layer, "weight_scale")
- and hasattr(tmp_layer, "weight_packed")
- and tmp_layer.weight_scale.dtype is torch.uint8
- and tmp_layer.weight_scale.shape[0] == 2048
- ), "Illegal MXFP4 packing name or data_type or shape"
- quantization_config = AutoConfig.from_pretrained(self.save_dir, trust_remote_code=True).quantization_config
- assert (
- quantization_config["format"] == "float-quantized"
- and quantization_config["config_groups"]["group_0"]["weights"]["is_mx"] is True
- and quantization_config["config_groups"]["group_0"]["weights"]["num_bits"] == 4
- ), f"Invalid MXFP4 quantization configuration: {quantization_config}"
- shutil.rmtree(self.save_dir, ignore_errors=True)
- def test_nvfp4_llmcompressor_format(self, tiny_opt_model_path, dataloader):
- scheme = "nvfp4"
+ # Initialize AutoRound for quantization
autoround = AutoRound(
- tiny_opt_model_path,
+ model,
+ tokenizer,
scheme=scheme,
- iters=2,
- seqlen=2,
- dataset=dataloader,
+ iters=0,
+ nsamples=2,
+ disable_opt_rtn=True,
)
- quantized_model_path = self.save_dir
- compressed_model, _ = autoround.quantize_and_save(output_dir=quantized_model_path, format="llm_compressor")
- tmp_layer = compressed_model.model.decoder.layers[1].self_attn.q_proj
- assert (
- hasattr(tmp_layer, "weight_scale")
- and hasattr(tmp_layer, "weight_global_scale")
- and hasattr(tmp_layer, "input_global_scale")
- and tmp_layer.weight_packed.dtype is torch.uint8
- and tmp_layer.weight_scale.dtype is torch.float8_e4m3fn
- and tmp_layer.weight_scale.shape[0] == 768
- ), "Illegal NVFP4 packing name or data_type or shape"
- quantization_config = AutoConfig.from_pretrained(
- quantized_model_path, trust_remote_code=True
- ).quantization_config
- assert (
- quantization_config["format"] == "nvfp4-pack-quantized"
- and quantization_config["config_groups"]["group_0"]["input_activations"]["num_bits"] == 4
- ), f"Invalid NVFP4 quantization configuration: {quantization_config}"
- shutil.rmtree(quantized_model_path, ignore_errors=True)
- # from vllm import LLM, SamplingParams
- # prompts = [
- # "The capital of France is",
- # "The future of AI is",
- # ]
- ## Create a sampling params object.
- # sampling_params = SamplingParams(temperature=0.8, top_p=0.95, max_tokens=20)
- # QUANTIZATION = "compressed-tensors"
- # llm = LLM(model=quantized_model_path,
- # # quantization=QUANTIZATION,
- # trust_remote_code=True,
- # tensor_parallel_size=1,
- # enforce_eager=True,
- # gpu_memory_utilization=0.7,
+
+ # Quantize and save the model to the temporary directory
+ quantized_model_path = f"{temp_dir}/tmp_autoround_{scheme}"
+ autoround.quantize_and_save(format="auto_round", output_dir=quantized_model_path)
+
+ # Perform inference with the quantized model
+ model = AutoModelForCausalLM.from_pretrained(
+ quantized_model_path,
+ torch_dtype="auto",
+ )
+ model.eval()
+ assert has_module(model, QMODULE_MAPPING[scheme]), f"Expected {QMODULE_MAPPING[scheme].__name__} in the model."
+
+ # Skip accuracy check for tiny model.
+
+ # tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
+ # prompt = "The capital of France is"
+ # encode = tokenizer.encode(prompt, return_tensors="pt")
+ # output_tokens = model.generate(
+ # encode,
+ # max_length=10,
# )
- # outputs = llm.generate(prompts, sampling_params)
- # # Print the outputs.
- # for output in outputs:
- # prompt = output.prompt
- # generated_text = output.outputs[0].text
- # if "France" in prompt:
- # assert "Paris" in generated_text
+ # output = tokenizer.decode(output_tokens[0], skip_special_tokens=True)
+ # assert "paris" in output.lower(), f"Expected 'Paris' in the output, but got: {output}"
+
+
+class TestAutoRound:
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
+ @pytest.fixture(autouse=True, scope="class")
+ def setup_and_teardown_class(self):
+ yield
+ shutil.rmtree("runs", ignore_errors=True)
def test_nvfp4_moe_actmax_rtn(self, tiny_deepseek_v2_model_path, dataloader):
# model_name = "/data0/deepseek-ai/DeepSeek-V2-Lite"
@@ -123,8 +106,11 @@ class TestAutoRound:
autoround.quantize()
quantized_model_path = self.save_dir
autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round")
- shutil.rmtree(quantized_model_path, ignore_errors=True)
+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path, torch_dtype="auto", device_map="auto")
+ print(model)
+ assert model is not None, "Failed to load the quantized model."
+ @pytest.mark.skip_ci(reason="Cannot test all case in CI; time-consuming")
def test_nvfp4_moe_actmax_ar(self, tiny_deepseek_v2_model_path, dataloader):
scheme = "nvfp4"
autoround = AutoRound(
@@ -139,10 +125,11 @@ class TestAutoRound:
autoround.quantize()
quantized_model_path = self.save_dir
autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round")
- shutil.rmtree(quantized_model_path, ignore_errors=True)
+ @pytest.mark.skip_ci(reason="Only tiny model is suggested")
+ @pytest.mark.skip_ci(reason="Time-consuming; Accuracy evaluation")
def test_qwen_moe_quant_infer(self, dataloader):
- model_name = get_model_path("qwen/Qwen1.5-MoE-A2.7B")
+ model_name = get_model_path("Qwen/Qwen1.5-MoE-A2.7B")
layer_config = {
"layers\.(?:[3-9]|1[0-9]|2[0-3])": {"bits": 16, "act_bits": 16},
}
@@ -163,4 +150,3 @@ class TestAutoRound:
from ...helpers import evaluate_accuracy
evaluate_accuracy(model, tokenizer, threshold=0.49, batch_size=16, task="piqa", limit=10)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
diff --git a/test/test_cuda/requirements.txt b/test/test_cuda/requirements.txt
index 47c3968ec..b85b06535 100644
--- a/test/test_cuda/requirements.txt
+++ b/test/test_cuda/requirements.txt
@@ -1,11 +1,12 @@
# pip install -v git+https://github.com/casper-hansen/AutoAWQ.git --no-build-isolation
-auto-gptq
+# auto-gptq
einops
# pip install -v git+https://github.com/ModelCloud/GPTQModel.git --no-build-isolation
+# pip install git+https://github.com/ggml-org/llama.cpp.git#subdirectory=gguf-py
lm_eval >= 0.4.10 # for transformers >= 5.0.0
optimum
pandas
pillow
torchvision
numba
-vllm
\ No newline at end of file
+sentencepiece
diff --git a/test/test_cuda/requirements_diffusion.txt b/test/test_cuda/requirements_diffusion.txt
index 55908f6ac..259530417 100644
--- a/test/test_cuda/requirements_diffusion.txt
+++ b/test/test_cuda/requirements_diffusion.txt
@@ -1,3 +1,4 @@
-diffusers
+diffusers @ git+https://github.com/huggingface/diffusers.git@main
image-reward
-clip
\ No newline at end of file
+clip
+optimum
diff --git a/test/test_cuda/requirements_vllm.txt b/test/test_cuda/requirements_vllm.txt
new file mode 100644
index 000000000..fbedb5bf7
--- /dev/null
+++ b/test/test_cuda/requirements_vllm.txt
@@ -0,0 +1,2 @@
+vllm
+lm_eval >= 0.4.10
diff --git a/test/test_cuda/schemes/test_scheme.py b/test/test_cuda/schemes/test_scheme.py
deleted file mode 100644
index 8ab78756b..000000000
--- a/test/test_cuda/schemes/test_scheme.py
+++ /dev/null
@@ -1,151 +0,0 @@
-import os
-import shutil
-
-import pytest
-import transformers
-from packaging import version
-
-from auto_round import AutoRound
-from auto_round.schemes import QuantizationScheme
-
-from ...helpers import get_model_path, save_tiny_model, transformers_version
-
-
-class TestAutoRound:
- save_dir = "./saved"
-
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
- yield
-
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- # Tuning tests
- def test_gguf(self, tiny_qwen_model_path):
- ar = AutoRound(tiny_qwen_model_path, scheme="W2A16", nsamples=1, iters=1)
- ar.quantize_and_save(self.save_dir, format="gguf:q4_k_m")
- assert ar.bits == 4
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- def test_w4a16(self, tiny_opt_model_path):
- ar = AutoRound(tiny_opt_model_path, scheme="W4A16", nsamples=1, iters=1)
- assert ar.bits == 4
- ar.quantize_and_save()
- model = transformers.AutoModelForCausalLM.from_pretrained("tmp_autoround", trust_remote_code=True)
- assert model is not None, "Model loading failed after quantization with W4A16 scheme"
-
- def test_w2a16(self, tiny_opt_model_path):
- ar = AutoRound(tiny_opt_model_path, scheme="W2A16", nsamples=1, iters=1)
- assert ar.bits == 2
- ar.quantize_and_save()
- model = transformers.AutoModelForCausalLM.from_pretrained("tmp_autoround", trust_remote_code=True)
- assert model is not None, "Model loading failed after quantization with W2A16 scheme"
-
- def test_mxfp4(self, tiny_opt_model_path):
- ar = AutoRound(tiny_opt_model_path, scheme="MXFP4_RCEIL", nsamples=1, iters=1)
- assert ar.bits == 4
- assert ar.act_bits == 4
- assert ar.data_type == "mx_fp"
- assert ar.act_data_type == "mx_fp_rceil"
- ar.quantize_and_save()
- model = transformers.AutoModelForCausalLM.from_pretrained("tmp_autoround", trust_remote_code=True)
- assert model is not None, "Model loading failed after quantization with MXFP4 scheme"
-
- def test_fp8_static(self, tiny_opt_model_path):
- ar = AutoRound(tiny_opt_model_path, scheme="FP8_STATIC", nsamples=1, iters=1)
- assert ar.bits == 8
- assert ar.act_bits == 8
- assert ar.data_type == "fp"
- assert ar.act_data_type == "fp"
- assert ar.group_size == -1
- assert ar.act_dynamic is False
- ar.quantize_and_save()
- model = transformers.AutoModelForCausalLM.from_pretrained("tmp_autoround", trust_remote_code=True)
- assert model is not None, "Model loading failed after quantization with FP8_STATIC scheme"
-
- ## RTN tests
- def test_w2a16_rtn(self, tiny_opt_model_path):
- ar = AutoRound(tiny_opt_model_path, scheme="W2A16", nsamples=1, iters=0)
- assert ar.bits == 2
- ar.quantize_and_save()
-
- def test_mxfp4_rtn(self, tiny_opt_model_path):
- ar = AutoRound(tiny_opt_model_path, scheme="MXFP4", nsamples=1, iters=0)
- assert ar.bits == 4
- assert ar.act_bits == 4
- assert ar.data_type == "mx_fp"
- assert ar.act_data_type == "mx_fp"
- ar.quantize_and_save()
-
- def test_fp8_static_rtn(self, tiny_opt_model_path):
- ar = AutoRound(tiny_opt_model_path, scheme="FP8_STATIC", nsamples=1, iters=0)
- assert ar.bits == 8
- assert ar.act_bits == 8
- assert ar.data_type == "fp"
- assert ar.act_data_type == "fp"
- assert ar.group_size == -1
- assert ar.act_dynamic is False
- ar.quantize_and_save()
-
- def test_scheme_in_layer_config(self):
- model_path = get_model_path("facebook/opt-125m")
- layer_config = {
- "model.decoder.layers.2.self_attn": {"bits": 2},
- "model.decoder.layers.3.self_attn.v_proj": "W8A16",
- "model.decoder.layers.4.self_attn.k_proj": QuantizationScheme.from_dict({"group_size": 64}),
- }
- ar = AutoRound(model_path, scheme="W3A16", nsamples=1, iters=1, layer_config=layer_config)
-
- ar.quantize_and_save()
- model = transformers.AutoModelForCausalLM.from_pretrained("tmp_autoround", trust_remote_code=True)
- assert model is not None, "Model loading failed after quantization with layer-specific schemes"
- for n, m in ar.model.named_modules():
- if n == "model.decoder.layers.2.self_attn.q_proj":
- assert m.bits == 2
- if n == "model.decoder.layers.2.self_attn.k_proj":
- assert m.bits == 2
- if n == "model.decoder.layers.3.self_attn.v_proj":
- assert m.bits == 8
- if n == "model.decoder.layers.4.self_attn.k_proj":
- assert m.group_size == 64
-
- @pytest.mark.skipif(
- transformers_version >= version.parse("5.0.0"), reason="transformers v5 MOE model has breaking changes"
- )
- def test_q2k_mixed(self):
- model_path = "/data0/MiroThinker-v1.5-30B"
- saved_tiny_model_path = save_tiny_model(
- model_path,
- "./tmp/tiny_qwen_model_path",
- num_layers=3,
- is_mllm=False,
- )
- autoround = AutoRound(
- saved_tiny_model_path,
- iters=0,
- nsamples=1,
- seqlen=16,
- disable_opt_rtn=True,
- )
- quantized_model_path = "./saved"
- autoround.quantize_and_save(output_dir=quantized_model_path, format="gguf:q2_k_mixed")
- gguf_file = os.listdir(quantized_model_path)[0]
- file_size = os.path.getsize(os.path.join(quantized_model_path, gguf_file)) / 1024**2
- assert abs(file_size - 1236) < 5.0
- from gguf.gguf_reader import GGUFReader
-
- gguf_model = GGUFReader(os.path.join(quantized_model_path, gguf_file))
- assert gguf_model.get_tensor(2).name == "blk.0.attn_v.weight"
- assert gguf_model.get_tensor(2).tensor_type.name == "Q4_K"
- assert gguf_model.get_tensor(9).name == "blk.0.ffn_up_exps.weight"
- assert gguf_model.get_tensor(9).tensor_type.name == "Q2_K"
-
- shutil.rmtree(saved_tiny_model_path, ignore_errors=True)
- shutil.rmtree(quantized_model_path, ignore_errors=True)
diff --git a/test/test_cuda/utils/__init__.py b/test/test_cuda/utils/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/test/test_hpu/test_quant_fp8.py b/test/test_hpu/test_quant_fp8.py
index eaaa61741..39f25fa37 100644
--- a/test/test_hpu/test_quant_fp8.py
+++ b/test/test_hpu/test_quant_fp8.py
@@ -13,7 +13,12 @@ MODEL_LIST = (
class TestAutoRound:
- save_dir = "./saved"
+
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
def check_nan_inf_in_tensor(self, tensor, name=""):
return torch.isnan(tensor).any() or torch.isinf(tensor).any()
@@ -32,4 +37,3 @@ class TestAutoRound:
), f"{name} has NaN or Inf in weights"
fp8_linear_count += 1
assert fp8_linear_count > 0, "No FP8 linear layer found in the quantized model"
- shutil.rmtree(self.save_dir, ignore_errors=True)
diff --git a/test/test_xpu/test_autoround.py b/test/test_xpu/test_autoround.py
index fb0dbe1ae..8c2ee5502 100644
--- a/test/test_xpu/test_autoround.py
+++ b/test/test_xpu/test_autoround.py
@@ -19,10 +19,15 @@ class TestAutoRoundXPU:
@classmethod
def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
pass
+ @pytest.fixture(autouse=True)
+ def _save_dir(self, tmp_path):
+ self.save_dir = str(tmp_path / "saved")
+ yield
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
def test_gptq_format(self, dataloader):
model_name = get_model_path("facebook/opt-125m")
model = AutoModelForCausalLM.from_pretrained(
@@ -41,7 +46,7 @@ class TestAutoRoundXPU:
seqlen=2,
dataset=dataloader,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path)
quantization_config = AutoRoundConfig(backend="auto")
@@ -73,7 +78,7 @@ class TestAutoRoundXPU:
seqlen=2,
dataset=dataloader,
)
- quantized_model_path = "./saved"
+ quantized_model_path = self.save_dir
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round:auto_awq")
quantization_config = AutoRoundConfig(backend="auto")