PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
fix CUDA UT (#2284)
Xin He039f027f527c
diff --git a/auto_round/utils/common.py b/auto_round/utils/common.pyindex 556f3f505..284bfee94 100644--- a/auto_round/utils/common.py+++ b/auto_round/utils/common.py@@ -42,7 +42,12 @@ def download_audiocaps_csv():import requestsurl = "https://raw.githubusercontent.com/cdjkim/audiocaps/master/dataset2.0/train.csv"- cache_dir = os.path.join(tempfile.gettempdir(), "audiocaps_cache")+ # Prefer AR_WORKSPACE environment variable for cache location when provided.+ ar_workspace = os.environ.get("AR_WORKSPACE")+ if ar_workspace:+ cache_dir = os.path.join(ar_workspace, "audiocaps_cache")+ else:+ cache_dir = os.path.join(tempfile.gettempdir(), "audiocaps_cache")os.makedirs(cache_dir, exist_ok=True)cache_file = os.path.join(cache_dir, "train.csv")diff --git a/auto_round/utils/device.py b/auto_round/utils/device.pyindex 884683d08..7a7f5cfa5 100644--- a/auto_round/utils/device.py+++ b/auto_round/utils/device.py@@ -321,7 +321,9 @@ def set_cuda_visible_devices(device: str):visible_devices = ",".join(pick_device)os.environ["CUDA_VISIBLE_DEVICES"] = visible_deviceselse:- os.environ["CUDA_VISIBLE_DEVICES"] = device+ # Use the cleaned/normalized device indices (no spaces, no type+ # prefixes) when initially setting the environment variable.+ os.environ["CUDA_VISIBLE_DEVICES"] = ",".join(devices)class override_cuda_device_capability(ContextDecorator):diff --git a/test/e2e/test_cuda/test_moe_accuracy.py b/test/e2e/test_cuda/test_moe_accuracy.pynew file mode 100644index 000000000..482e9d9c7--- /dev/null+++ b/test/e2e/test_cuda/test_moe_accuracy.py@@ -0,0 +1,60 @@+# Copyright (c) 2026 Intel Corporation+#+# 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.++from __future__ import annotations++from test.helpers import get_model_path++import pytest+import torch+from transformers import AutoModelForCausalLM, AutoTokenizer++from auto_round import AutoRound++pytestmark = [+ pytest.mark.e2e,+ pytest.mark.skip_ci(reason="Real MoE accuracy checks are large and GPU-hungry"),+ pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is required for e2e MoE accuracy checks"),+]+++def test_qwen_moe_nvfp4_accuracy(dataloader):+ free_gib = torch.cuda.mem_get_info()[0] / 1024**3+ if free_gib < 24:+ pytest.skip(f"only {free_gib:.1f} GiB free CUDA memory, need at least 24 GiB for Qwen1.5-MoE-A2.7B")++ model_name = get_model_path("Qwen/Qwen1.5-MoE-A2.7B")+ layer_config = {+ r"layers\.(?:[3-9]|1[0-9]|2[0-3])": {"bits": 16, "act_bits": 16},+ }++ autoround = AutoRound(+ model_name,+ scheme="nvfp4",+ iters=1,+ seqlen=3,+ nsamples=2,+ dataset=dataloader,+ layer_config=layer_config,+ )+ _, quantized_model_path = autoround.quantize_and_save(+ output_dir="tmp_qwen_moe_nvfp4", 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 test.helpers import evaluate_accuracy++ evaluate_accuracy(model, tokenizer, threshold=0.49, batch_size=16, task="piqa", limit=10)diff --git a/test/unit/common/utils/test_common_utils.py b/test/unit/common/utils/test_common_utils.pyindex 40cff2ba0..a47f592b0 100644--- a/test/unit/common/utils/test_common_utils.py+++ b/test/unit/common/utils/test_common_utils.py@@ -43,19 +43,29 @@ class TestDownloadAudiocapsCsv:from auto_round.utils.common import download_audiocaps_csv- # Create a temporary cached file- cache_dir = os.path.join(tempfile.gettempdir(), "audiocaps_cache")- os.makedirs(cache_dir, exist_ok=True)- cache_file = os.path.join(cache_dir, "train.csv")-- with open(cache_file, "w") as f:- f.write("audio_id,audio_file,caption\ntest,test.wav,a test caption")-- # Should use cached file without network call- with patch("requests.get") as mock_get:- result = download_audiocaps_csv()- assert result == cache_file- mock_get.assert_not_called()+ # Set AR_WORKSPACE so the function uses our test tmp directory+ prev_ar_ws = os.environ.get("AR_WORKSPACE")+ os.environ["AR_WORKSPACE"] = "./tmp"+ try:+ # Create a temporary cached file+ cache_dir = os.path.join("./tmp", "audiocaps_cache")+ os.makedirs(cache_dir, exist_ok=True)+ cache_file = os.path.join(cache_dir, "train.csv")++ with open(cache_file, "w") as f:+ f.write("audio_id,audio_file,caption\ntest,test.wav,a test caption")++ # Should use cached file without network call+ with patch("requests.get") as mock_get:+ result = download_audiocaps_csv()+ assert result == cache_file+ mock_get.assert_not_called()+ finally:+ # Restore previous AR_WORKSPACE+ if prev_ar_ws is None:+ del os.environ["AR_WORKSPACE"]+ else:+ os.environ["AR_WORKSPACE"] = prev_ar_wsclass TestCompareVersions:diff --git a/test/unit/common/utils/test_device.py b/test/unit/common/utils/test_device.pyindex df6a63ec7..836652807 100644--- a/test/unit/common/utils/test_device.py+++ b/test/unit/common/utils/test_device.py@@ -1624,7 +1624,7 @@ class TestSetCudaVisibleDevicesExtra:"""Spaces in numeric input should still work (the function strips)."""from auto_round.utils.device import set_cuda_visible_devices- original = os.environ.get("CUDA_VISIBLE_DEVICES")+ original = os.environ.pop("CUDA_VISIBLE_DEVICES", None)try:set_cuda_visible_devices("0 ")assert os.environ.get("CUDA_VISIBLE_DEVICES") == "0"diff --git a/test/unit/test_cpu/models/test_block_names.py b/test/unit/test_cpu/models/test_block_names.pyindex 9d6d1b000..c97999593 100644--- a/test/unit/test_cpu/models/test_block_names.py+++ b/test/unit/test_cpu/models/test_block_names.py@@ -66,15 +66,16 @@ class TestQuantizationBlocks:assert len(block_name) == 1assert block_name == get_block_names(model)- def test_moe(self):+ def test_moe(self, tiny_qwen_moe_model_path):+ from transformers import AutoConfig+from auto_round.utils import get_block_names- model_name = get_model_path("Qwen/Qwen1.5-MoE-A2.7B")- # config = AutoConfig.from_pretrained(model_name)- model = AutoModelForCausalLM.from_pretrained(model_name)+ config = AutoConfig.from_pretrained(tiny_qwen_moe_model_path, trust_remote_code=True)+ model = AutoModelForCausalLM.from_config(config)block_name = get_block_names(model)block_name_2 = get_block_names(model, quant_vision=True)assert block_name == block_name_2assert len(block_name_2) == 1- assert "model.layers.23" == block_name_2[0][-1]+ assert block_name_2[0][-1] == "model.layers.1"diff --git a/test/unit/test_cuda/quantization/test_mxfp_nvfp.py b/test/unit/test_cuda/quantization/test_mxfp_nvfp.pyindex dbbcd6300..25c3c54cd 100644--- a/test/unit/test_cuda/quantization/test_mxfp_nvfp.py+++ b/test/unit/test_cuda/quantization/test_mxfp_nvfp.py@@ -126,30 +126,3 @@ class TestAutoRound:autoround.quantize()quantized_model_path = self.save_dirautoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round")-- @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")- layer_config = {- r"layers\.(?:[3-9]|1[0-9]|2[0-3])": {"bits": 16, "act_bits": 16},- }- scheme = "nvfp4"- autoround = AutoRound(- model_name,- scheme=scheme,- iters=1,- seqlen=3,- nsamples=2,- dataset=dataloader,- layer_config=layer_config,- )- quantized_model_path = self.save_dir- _, quantized_model_path = 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 test.helpers import evaluate_accuracy-- evaluate_accuracy(model, tokenizer, threshold=0.49, batch_size=16, task="piqa", limit=10)