PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
Apply autocast only when mixed precision is enabled (#2393)
Shubham Padkonde3f6c81905038
diff --git a/auto_round/algorithms/quantization/sign_round/quantizer.py b/auto_round/algorithms/quantization/sign_round/quantizer.pyindex 25e7d5457..278240c87 100644--- a/auto_round/algorithms/quantization/sign_round/quantizer.py+++ b/auto_round/algorithms/quantization/sign_round/quantizer.py@@ -141,7 +141,7 @@ class SignRoundQuantizer(BaseQuantizer):):autocast_ctx = (nullcontext()- if self.model_context.amp+ if not self.model_context.ampelse autocast(device_type=str(device).split(":")[0], dtype=self.model_context.amp_dtype))if valid_token_mask:diff --git a/test/unit/common/algorithms/test_autocast_context.py b/test/unit/common/algorithms/test_autocast_context.pynew file mode 100644index 000000000..558ea9fc4--- /dev/null+++ b/test/unit/common/algorithms/test_autocast_context.py@@ -0,0 +1,55 @@+# 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.++"""The loss is computed under autocast only when mixed precision is enabled."""++import warnings+from types import SimpleNamespace++import pytest+import torch++from auto_round.algorithms.quantization.sign_round.quantizer import SignRoundQuantizer+++def _get_loss(amp: bool, amp_dtype: torch.dtype):+ quantizer = SimpleNamespace(model_context=SimpleNamespace(amp=amp, amp_dtype=amp_dtype))+ pred = torch.ones(2, 4)+ ref = torch.zeros(2, 4)++ return SignRoundQuantizer._get_loss(+ quantizer,+ pred,+ ref,+ indices=torch.tensor([0, 1]),+ loss_func=torch.nn.functional.mse_loss,+ device="cpu",+ )+++def test_no_autocast_when_amp_is_disabled():+ # Without mixed precision `amp_dtype` is float32, which CPU autocast does+ # not support: entering it warns and disables itself.+ with warnings.catch_warnings():+ warnings.simplefilter("error", UserWarning)+ loss = _get_loss(amp=False, amp_dtype=torch.float32)++ assert torch.isclose(loss, torch.tensor(1.0))++[email protected]("amp_dtype", [torch.bfloat16, torch.float32])+def test_loss_is_finite_with_amp_enabled(amp_dtype):+ loss = _get_loss(amp=True, amp_dtype=amp_dtype)++ assert torch.isfinite(loss)