PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
perf: avoid unused SVD reconstruction and select the CUDA driver in SVDQuant (#2356)
Wang, Chang903ba0ce4535
diff --git a/auto_round/algorithms/transforms/svdquant/apply.py b/auto_round/algorithms/transforms/svdquant/apply.pyindex 8257e7ceb..b1a767801 100644--- a/auto_round/algorithms/transforms/svdquant/apply.py+++ b/auto_round/algorithms/transforms/svdquant/apply.py@@ -29,8 +29,8 @@ from auto_round.algorithms.transforms.svdquant.config import SVDQuantConfigfrom auto_round.algorithms.transforms.svdquant.residual import (ActivationQuantScheme,ResidualQuantScheme,+ compute_svd_factors,iterate_residual_decomposition,- truncated_svd,)from auto_round.algorithms.transforms.svdquant.smooth import (SmoothCandidate,@@ -45,6 +45,7 @@ from auto_round.algorithms.transforms.svdquant.smooth_adapters import SmoothSearfrom auto_round.algorithms.transforms.svdquant.wrapper import SVDQuantLinearfrom auto_round.logger import loggerfrom auto_round.schemes import QuantizationScheme+from auto_round.utils.device_manager import device_managerfrom auto_round.utils.model import map_nested_tensors_SCHEME_ATTRS = set(QuantizationScheme.get_attributes())@@ -52,6 +53,26 @@ _RUNTIME_QUANT_ATTRS = {"scale_dtype", "weight_global_scale", "tuning_device"}_MXFP4_ALIASES = frozenset({"mx_fp", "mx_fp4", "mx_fp4e2m1"})+def _select_svd_driver(device: torch.device) -> str | None:+ """Select a CUDA driver once using a small matrix on the execution device."""+ if device.type != "cuda" or torch.version.cuda is None:+ return None+ probe = torch.tensor([[1.0, 2.0], [3.0, 5.0]], device=device, dtype=torch.float32)+ for driver in ("gesvda", "gesvdj", "gesvd"):+ try:+ torch.linalg.svd(probe, full_matrices=False, driver=driver)+ torch.cuda.synchronize(device)+ except torch.OutOfMemoryError:+ raise+ except RuntimeError as exc:+ if driver == "gesvd":+ raise+ logger.debug("SVDQuant driver %s probe failed: %s", driver, exc)+ continue+ logger.info("SVDQuant selected SVD driver %s on %s.", driver, device)+ return driver++def _detach_to_cpu(value: Any) -> Any:return map_nested_tensors(value, lambda tensor: tensor.detach().to("cpu", copy=True))@@ -114,6 +135,7 @@ class SVDQuantTransform(BasePreprocessor):def __init__(self, config: SVDQuantConfig) -> None:super().__init__(config)+ self._svd_driver = Noneself._configured_block_names: tuple[str, ...] = ()self._block_groups: dict[str, list[SmoothSearchGroup]] = {}self._smooth_calibration: dict[str, SmoothGroupCalibration] = {}@@ -133,6 +155,11 @@ class SVDQuantTransform(BasePreprocessor):nblocks = getattr(orchestrator, "nblocks", 1)if nblocks != 1:raise ValueError(f"SVDQuant requires nblocks=1, got nblocks={nblocks}.")+ # One CLI command owns one compressor, including dual-transformer pipelines.+ # Rebinding algorithms for another transformer must reuse its SVD driver.+ if not hasattr(orchestrator, "_svdquant_svd_driver"):+ orchestrator._svdquant_svd_driver = _select_svd_driver(torch.device(device_manager.device))+ self._svd_driver = orchestrator._svdquant_svd_driverquant_block_list = getattr(orchestrator, "quant_block_list", None) or ()self._configured_block_names = tuple(block_name for block_group in quant_block_list for block_name in block_group@@ -395,7 +422,7 @@ class SVDQuantTransform(BasePreprocessor):stacked = torch.cat(weights, dim=0)output_sizes = [projection.out_features for projection in group.projections]rank = min(self.config.rank, *stacked.shape)- _, down, up = truncated_svd(stacked, rank)+ down, up = compute_svd_factors(stacked, rank, driver=self._svd_driver)low_rank_dtype = self._resolve_low_rank_dtype(group.projections[0].weight.dtype)deployed_down = down.to(low_rank_dtype)deployed_up = up.to(low_rank_dtype)@@ -430,7 +457,7 @@ class SVDQuantTransform(BasePreprocessor):rank = min(self.config.rank, *stacked.shape)low_rank_dtype = self._resolve_low_rank_dtype(group.projections[0].weight.dtype)if self.config.residual_iters == 1:- _, down, up = truncated_svd(stacked, rank)+ down, up = compute_svd_factors(stacked, rank, driver=self._svd_driver)deployed_down = down.to(low_rank_dtype)deployed_up = up.to(low_rank_dtype)low_rank = deployed_up.float() @ deployed_down.float()@@ -463,7 +490,7 @@ class SVDQuantTransform(BasePreprocessor):best_error = float("inf")activation_scheme = self._group_activation_quant_scheme(group)for iteration in range(1, self.config.residual_iters + 1):- _, down, up = truncated_svd(stacked - quantized_residual, rank)+ down, up = compute_svd_factors(stacked - quantized_residual, rank, driver=self._svd_driver)deployed_down = down.to(low_rank_dtype)deployed_up = up.to(low_rank_dtype)low_rank = deployed_up.float() @ deployed_down.float()@@ -522,7 +549,7 @@ class SVDQuantTransform(BasePreprocessor):low_rank_dtype = self._resolve_low_rank_dtype(group.projections[0].weight.dtype)if self.config.residual_iters == 1:- _, down, up = truncated_svd(stacked, rank)+ down, up = compute_svd_factors(stacked, rank, driver=self._svd_driver)deployed_down = down.to(low_rank_dtype)deployed_up = up.to(low_rank_dtype)deployed_low_rank = deployed_up.float() @ deployed_down.float()@@ -542,6 +569,7 @@ class SVDQuantTransform(BasePreprocessor):early_stop=self.config.residual_early_stop,residual_dtype=group.projections[0].weight.dtype,low_rank_dtype=low_rank_dtype,+ driver=self._svd_driver,)deployed_down = result.downdeployed_up = result.updiff --git a/auto_round/algorithms/transforms/svdquant/residual.py b/auto_round/algorithms/transforms/svdquant/residual.pyindex b9f265c2d..461f6763b 100644--- a/auto_round/algorithms/transforms/svdquant/residual.py+++ b/auto_round/algorithms/transforms/svdquant/residual.py@@ -166,8 +166,10 @@ def rtn_qdq_activation(activation: torch.Tensor, scheme: ActivationQuantScheme)@torch.inference_mode()-def truncated_svd(weight: torch.Tensor, rank: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:- """Return a rank-limited reconstruction and its shared down/up factors."""+def compute_svd_factors(+ weight: torch.Tensor, rank: int, *, driver: str | None = None+) -> tuple[torch.Tensor, torch.Tensor]:+ """Return shared down/up factors without materializing a dense reconstruction."""if weight.ndim != 2:raise ValueError(f"SVDQuant expects a two-dimensional weight matrix, got shape={tuple(weight.shape)}.")max_rank = min(weight.shape)@@ -176,15 +178,24 @@ def truncated_svd(weight: torch.Tensor, rank: int) -> tuple[torch.Tensor, torch.out_features, in_features = weight.shapeif rank == 0:- low_rank = torch.zeros_like(weight)down_weight = torch.empty((0, in_features), dtype=weight.dtype, device=weight.device)up_weight = torch.empty((out_features, 0), dtype=weight.dtype, device=weight.device)- return low_rank, down_weight, up_weight+ return down_weight, up_weight- u, s, vh = torch.linalg.svd(weight, full_matrices=False)+ u, s, vh = torch.linalg.svd(weight, full_matrices=False, driver=driver if weight.is_cuda else None)down_weight = vh[:rank, :]up_weight = u[:, :rank] * s[:rank].reshape(1, -1)- return up_weight @ down_weight, down_weight, up_weight+ return down_weight, up_weight++[email protected]_mode()+def truncated_svd(+ weight: torch.Tensor, rank: int, *, driver: str | None = None+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ """Return a rank-limited reconstruction and its shared down/up factors."""+ down_weight, up_weight = compute_svd_factors(weight, rank, driver=driver)+ low_rank = torch.zeros_like(weight) if rank == 0 else up_weight @ down_weight+ return low_rank, down_weight, up_weight@torch.inference_mode()@@ -197,6 +208,7 @@ def iterate_residual_decomposition(early_stop: bool,residual_dtype: torch.dtype,low_rank_dtype: torch.dtype,+ driver: str | None = None,) -> ResidualDecomposition:"""Select the lowest weight-MSE residual/low-rank candidate after deployment casting."""if type(iterations) is not int or iterations < 1:@@ -209,7 +221,7 @@ def iterate_residual_decomposition(best_iteration = Nonefor iteration in range(1, iterations + 1):- low_rank, down, up = truncated_svd(weight - quantized_residual, rank)+ low_rank, down, up = truncated_svd(weight - quantized_residual, rank, driver=driver)if not all(torch.isfinite(tensor).all() for tensor in (low_rank, down, up)):break