PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
add opt_rtn support for mxfp4 and nvfp4 (#2100)
Wenhua Cheng41cca72fc545
diff --git a/auto_round/algorithms/composer.py b/auto_round/algorithms/composer.pyindex 015224ec6..7d5dd76f4 100644--- a/auto_round/algorithms/composer.py+++ b/auto_round/algorithms/composer.py@@ -202,6 +202,9 @@ class AlgorithmComposer:):logger.info("Block-forward torch.compile is disabled because an enabled rotation is incompatible.")+ if "nv_fp" in orchestrator.data_type:+ can_compile_block_forward = False+# Bind compressor-level infrastructure (set before _build_quantizer is called).self.block_forward = (BlockForwardRunner.from_orchestrator(orchestrator, enable_torch_compile=can_compile_block_forward)@@ -440,7 +443,7 @@ class AlgorithmComposer:if is_nv_fp(act_data_type) or not act_dynamic:set_amax_for_all_moe_layers(block, attr_name="act_max")- update_block_global_scale_if_needed(block_ctx.model, data_type, group_size)+ update_block_global_scale_if_needed(block, data_type, group_size)if q_inputs is not None and fp_inputs is not q_inputs:clear_memory(fp_inputs)diff --git a/auto_round/algorithms/quantization/rtn/quantizer.py b/auto_round/algorithms/quantization/rtn/quantizer.pyindex 0bff58eb8..6fee985fd 100644--- a/auto_round/algorithms/quantization/rtn/quantizer.py+++ b/auto_round/algorithms/quantization/rtn/quantizer.py@@ -71,16 +71,7 @@ class RTNQuantizer(BaseQuantizer):class OptimizedRTNQuantizer(RTNQuantizer):def __init__(self, config: RTNConfig) -> None:- BaseQuantizer.__init__(self, config)- if (- self.scheme is not None- and self.scheme.data_type- and ("nv_fp" in self.scheme.data_type or "mx_fp" in self.scheme.data_type)- ):- logger.warning_once(- "opt-rtn does not support NVFP or MXFP. It behaves the same as RTN but is much slower. "- "Please use RTN instead."- )+ super().__init__(config)def can_compile_block_forward(self):return Falsediff --git a/auto_round/data_type/mxfp.py b/auto_round/data_type/mxfp.pyindex 0b8b435cf..8f924acd9 100644--- a/auto_round/data_type/mxfp.py+++ b/auto_round/data_type/mxfp.py@@ -99,26 +99,137 @@ def qdq_mxfp(tensor, max_val, max_norm, emax, ebits, mbits):return tensor * scale-def search_mx_scale(tensor, bits, qw=None):- data_type = "mx_fp" + str(bits)[email protected]_grad()+def search_mx_scale(tensor, bits, qw=None, data_type=None):+ if data_type is None or data_type not in MXFP_FORMAT_CACHE:+ data_type = "mx_fp" + str(bits)+ebits, mbits, emax, max_norm, _ = MXFP_FORMAT_CACHE[data_type]+tensor = tensor.to(torch.float32)+max_val, _ = torch.max(torch.abs(tensor), dim=-1, keepdim=True)- qdq_t = qdq_mxfp(tensor, max_val, max_norm, emax, ebits, mbits)- best_loss = torch.sum((qdq_t - tensor) ** 2 * qw, dim=-1)++ # Reusable buffers+ scale_buf = torch.empty_like(max_val)+ buf = torch.empty_like(tensor)scales = torch.ones_like(max_val)- for scale_value in range(50, 152):- tmp_scale = scale_value / 100.0- if tmp_scale == 1.0:- continue- tmp_qdq_t = qdq_mxfp(tensor, max_val * tmp_scale, max_norm, emax, ebits, mbits)- loss = torch.sum((tmp_qdq_t - tensor) ** 2 * qw, dim=-1)++ best_loss = torch.empty(+ tensor.shape[:-1],+ dtype=tensor.dtype,+ device=tensor.device,+ )+ loss = torch.empty_like(best_loss)++ def compute_loss(qdq_tensor, out):+ torch.sub(qdq_tensor, tensor, out=buf)+ buf.pow_(2)+ if qw is not None and not isinstance(qw, (int, float)):+ buf.mul_(qw)+ elif qw != 1.0:+ buf.mul_(qw)+ torch.sum(buf, dim=-1, out=out)++ # Baseline (exp_offset = 0)+ qdq_t = qdq_mxfp(+ tensor,+ max_val,+ max_norm,+ emax,+ ebits,+ mbits,+ )+ compute_loss(qdq_t, best_loss)++ # MX shared exponent only changes when crossing powers of two.+ # exp_offset = 0 has already been evaluated.+ for tmp_scale in (0.5, 2.0):+ # for scale_value in range(50, 152):+ # tmp_scale = scale_value / 100.0+ # if tmp_scale == 1.0:+ # continue+ torch.mul(max_val, tmp_scale, out=scale_buf)++ qdq_t = qdq_mxfp(+ tensor,+ scale_buf,+ max_norm,+ emax,+ ebits,+ mbits,+ )++ compute_loss(qdq_t, loss)+replace_id = loss < best_lossscales[replace_id] = tmp_scalebest_loss[replace_id] = loss[replace_id]+return scales+def quant_mx_opt_rtn(+ tensor,+ bits=4,+ group_size=32,+ v=0,+ mantissa_rounding="even",+ data_type="mx_fp",+ imatrix=None,+ **kwargs,+):+ from auto_round.data_type.gguf import _imatrix_handle_zero++ tensor, orig_shape, pad_len = reshape_pad_tensor_by_group_size(tensor, group_size)+ data_type = data_type if data_type in MXFP_FORMAT_CACHE else "mx_fp" + str(bits)+ ebits, mbits, emax, max_norm, _ = MXFP_FORMAT_CACHE[data_type]++ orig_dtype = tensor.dtype+ tensor = tensor.to(torch.float32)++ if imatrix is None:+ qw = 1.0+ else:+ imatrix = imatrix.reshape(1, -1)+ imatrix = reshape_pad_tensor_by_group_size(imatrix, group_size, val=1e-5)[0].view(1, -1)+ imatrix = imatrix.expand(tensor.numel() // imatrix.numel(), -1)+ imatrix = imatrix.reshape(tensor.shape)+ imatrix = _imatrix_handle_zero(imatrix, tensor, bits, group_size)+ qw = imatrix++ max_scales = search_mx_scale(tensor, bits, qw=qw, data_type=data_type)++ max_val = torch.amax(torch.abs(tensor), dim=-1, keepdim=True)+ max_val.mul_(max_scales)++ shared_exp = torch.where(max_val == 0, torch.ones_like(max_val), torch.log2(max_val))+ shared_exp.floor_()++ scale_emax = 2.0 ** (8 - 1) - 1+ shared_exp.sub_(emax).clamp_(+ min=-scale_emax,+ max=scale_emax,+ )++ scale = torch.pow(2.0, shared_exp)++ tensor.div_(scale)+ if v != 0:+ tensor.add_(v)++ tensor.clamp_(min=-max_norm, max=max_norm)+ tensor = quant_element(tensor, ebits, mbits, max_norm, mantissa_rounding)+ tensor.mul_(scale)+ tensor = revert_tensor_by_pad(+ tensor,+ orig_shape=orig_shape,+ pad_len=pad_len,+ )++ return tensor.to(orig_dtype), shared_exp.to(orig_dtype), None++def quant_mx(tensor,bits=4,@@ -234,7 +345,9 @@ def quant_mx_rceil(for key in MXFP_FORMAT_CACHE.keys():QUANT_FUNC_WITH_DTYPE[key] = quant_mxQUANT_FUNC_WITH_DTYPE[key + "_rceil"] = quant_mx_rceil+ QUANT_FUNC_WITH_DTYPE["opt_rtn_" + key] = quant_mx_opt_rtnQUANT_FUNC_WITH_DTYPE["mx_fp_rceil"] = quant_mx_rceil+QUANT_FUNC_WITH_DTYPE["opt_rtn_mx_fp"] = quant_mx_opt_rtnif __name__ == "__main__":data = torch.tensor([0.0, 0.25, 0.4, 0.75, 1.25, 1.4, 1.75, 2.5, 2.9, 3.5, 5.0, 5.1])diff --git a/auto_round/data_type/nvfp.py b/auto_round/data_type/nvfp.pyindex 84f356c42..f9f8a88fe 100644--- a/auto_round/data_type/nvfp.py+++ b/auto_round/data_type/nvfp.py@@ -15,6 +15,7 @@import torchfrom auto_round.data_type.fp8 import float8_e4m3fn_ste+from auto_round.data_type.gguf import _imatrix_handle_zerofrom auto_round.data_type.register import register_dtypefrom auto_round.data_type.utils import reshape_pad_tensor_by_group_size, revert_tensor_by_pad, round_stefrom auto_round.logger import logger@@ -79,24 +80,6 @@ def ref_nvfp4_quant(x, global_scale, block_size=16, v=0, scale_coeff=1.0):return (cast_to_fp4(clipped_x) * get_reciprocal(output_scale)).reshape(m, n), scale-def search_nvfp4_scale(tensor, bits=4, qw=None):- tensor = tensor.to(torch.float32)- qdq_t, dummy_scale, _ = nv_fp4(tensor, bits=bits, group_size=16, v=0, max_scale=1.0)- best_loss = torch.sum((qdq_t - tensor) ** 2 * qw, dim=-1)- scales = torch.ones_like(dummy_scale)- for scale_value in range(50, 152):- tmp_scale = scale_value / 100.0- if tmp_scale == 1.0:- continue- scales_new = torch.ones_like(dummy_scale) * tmp_scale- tmp_qdq_t, _, _ = nv_fp4(tensor, bits=bits, group_size=16, v=0, max_scale=scales_new)- loss = torch.sum((tmp_qdq_t - tensor) ** 2 * qw, dim=-1)- replace_id = loss < best_loss- scales[replace_id] = scales_new[replace_id]- best_loss[replace_id] = loss[replace_id]- return scales--@register_dtype("nv_fp4")def nv_fp4(tensor, bits=4, group_size=16, v=0, global_scale=None, max_scale=1.0, init_scale=1.0, **kwargs):orig_dtype = tensor.dtype@@ -258,6 +241,196 @@ def fp4_v2(tensor, bits=4, group_size=32, v=0, max_scale=1.0, **kwargs):return qdq_res.to(orig_dtype), scale, None+@register_dtype("nv_fp4_rtn")+def nv_fp4_rtn(tensor, bits=4, group_size=16, v=0, global_scale=None, max_scale=1.0, init_scale=1.0, **kwargs):+ orig_dtype = tensor.dtype+ init_scale = 1.0 if init_scale is None else init_scale+ tensor, orig_shape, pad_len = reshape_pad_tensor_by_group_size(tensor, group_size)+ if global_scale is None:+ tensor_max = tensor.abs().max().to(torch.float32)+ global_scale = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX * get_reciprocal(tensor_max)+ global_scale = global_scale.to(device=tensor.device, dtype=torch.float32)+ if isinstance(max_scale, torch.Tensor):+ max_scale = max_scale.view(-1).to(tensor.device)+ if isinstance(init_scale, torch.Tensor):+ init_scale = init_scale.view(-1).to(tensor.device)+ qdq_res, scale = ref_nvfp4_quant_inplace(tensor, global_scale, group_size, v, scale_coeff=max_scale * init_scale)+ qdq_res = revert_tensor_by_pad(qdq_res, orig_shape=orig_shape, pad_len=pad_len)+ return qdq_res.to(orig_dtype), scale, None+++@torch._dynamo.disable()+def to_float8_e4m3fn(tensor):+ return tensor.to(torch.float8_e4m3fn).to(torch.float32)+++def ref_nvfp4_quant_inplace(+ x,+ global_scale,+ block_size=16,+ v=0,+ scale_coeff=1.0,+ out=None,+):+ assert global_scale.dtype == torch.float32+ assert x.ndim == 2++ m, n = x.shape++ if isinstance(scale_coeff, torch.Tensor):+ scale_coeff = scale_coeff.view(-1, 1).to(x.device)++ # vec_max: [m, 1]+ vec_max = torch.amax(torch.abs(x), dim=-1, keepdim=True).float()++ if isinstance(scale_coeff, torch.Tensor):+ vec_max.mul_(scale_coeff)+ else:+ vec_max.mul_(scale_coeff)++ # scale: [m,1]+ scale = global_scale * (vec_max * get_reciprocal(FLOAT4_E2M1_MAX))++ scale.clamp_(+ min=FLOAT8_E4M3_MIN,+ max=FLOAT8_E4M3_MAX,+ )++ scale = to_float8_e4m3fn(scale)++ # output_scale reuse scale buffer+ output_scale = get_reciprocal(scale * get_reciprocal(global_scale))++ # allocate once+ if out is None:+ out = torch.empty_like(x, dtype=torch.float32)++ # out = x * output_scale+ out.copy_(x)+ out.mul_(output_scale)++ if v != 0:+ out.add_(v)++ # clamp inplace+ out.clamp_(-6.0, 6.0)++ # fp4 cast+ out = cast_to_fp4(out) * get_reciprocal(output_scale)++ return out.reshape(m, n), scale+++def search_nvfp4_scale(tensor, bits=4, qw=None):+ tensor_fp32 = tensor.float()++ qdq_t, scale, _ = nv_fp4(+ tensor_fp32,+ bits=bits,+ group_size=16,+ v=0,+ max_scale=1.0,+ )++ # loss buffer+ diff = torch.empty_like(tensor_fp32)+ loss = torch.empty_like(tensor_fp32[..., 0])++ diff.copy_(qdq_t)+ diff.sub_(tensor_fp32)+ diff.mul_(diff)+ diff.mul_(qw)+ loss.copy_(diff.sum(dim=-1))++ best_loss = loss.clone()++ # scale buffer reuse+ best_scale = torch.ones_like(scale)++ # inplace modify+ test_scale = torch.empty_like(scale)++ for scale_value in range(50, 152):+ tmp_scale = scale_value / 100.0++ if tmp_scale == 1.0:+ continue++ test_scale.fill_(tmp_scale)++ tmp_qdq, _, _ = nv_fp4_rtn(+ tensor_fp32,+ bits=bits,+ group_size=16,+ v=0,+ max_scale=test_scale,+ )++ diff.copy_(tmp_qdq)+ diff.sub_(tensor_fp32)+ diff.mul_(diff)+ diff.mul_(qw)++ loss.copy_(diff.sum(dim=-1))++ mask = loss < best_loss++ best_loss[mask] = loss[mask]+ best_scale[mask] = test_scale[mask]++ return best_scale+++@register_dtype("opt_rtn_nv_fp4")+def opt_rtn_fast_nvfp4(+ tensor,+ bits=4,+ group_size=16,+ v=0,+ global_scale=None,+ max_scale=1.0,+ imatrix=1.0,+ **kwargs,+):+ tensor, orig_shape, pad_len = reshape_pad_tensor_by_group_size(tensor, group_size)+ if imatrix is None:+ qw = 1.0+ else:+ imatrix = imatrix.reshape(1, -1)+ imatrix = reshape_pad_tensor_by_group_size(imatrix, group_size, val=1e-5)[0].view(1, -1)+ imatrix = imatrix.expand(tensor.numel() // imatrix.numel(), -1)+ imatrix = imatrix.reshape(tensor.shape)+ imatrix = _imatrix_handle_zero(imatrix, tensor, bits, group_size)+ qw = imatrix++ init_scale = search_nvfp4_scale(tensor, 4, qw)+ tensor = revert_tensor_by_pad(tensor, orig_shape, pad_len)+ return nv_fp4_rtn(tensor, bits, group_size, v, global_scale, max_scale, init_scale=init_scale)+++@register_dtype("rtn_nv_fp4_with_static_gs")+def rtn_nv_fp4_with_static_gs(tensor, bits=4, group_size=16, v=0, tensor_max=None, **kwargs):+ if tensor is None or tensor.numel() == 0:+ return tensor, None, None+ orig_dtype = tensor.dtype+ tensor, orig_shape, pad_len = reshape_pad_tensor_by_group_size(tensor, group_size)+ if tensor_max is None:+ tensor_max = tensor.abs().max().to(torch.float32)+ else:+ if not isinstance(tensor_max, torch.Tensor):+ tensor_max = torch.tensor(tensor_max, device=tensor.device, dtype=torch.float32)+ else:+ tensor_max = tensor_max.to(device=tensor.device, dtype=torch.float32)+ if tensor_max.numel() != 1:+ tensor_max = tensor_max.abs().max()++ global_scale = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX * get_reciprocal(tensor_max)+ global_scale = global_scale.to(tensor.device)+ qdq_res, scale = ref_nvfp4_quant_inplace(tensor, global_scale, group_size, v)+ qdq_res = revert_tensor_by_pad(qdq_res, orig_shape=orig_shape, pad_len=pad_len)+ return qdq_res.to(orig_dtype), scale, None++if __name__ == "__main__":data = torch.tensor([0.0, 0.25, 0.4, 0.75, 1.25, 1.4, 1.75, 2.5, 2.9, 3.5, 5.0, 5.1, 6.0, 6.2, 8.9])data1 = cast_to_fp4(data)diff --git a/docs/opt_rtn.md b/docs/opt_rtn.mdindex 354a397c3..01440cbb8 100644--- a/docs/opt_rtn.md+++ b/docs/opt_rtn.md@@ -1,3 +1,31 @@+### MXFP4/NVFP4 Results+MXFP4++| Model | ARC-c | ARC-e | BoolQ | Hella | LAMB | MMLU | OBQA | PIQA | Truth. | Wino | GSM8K strict | AVG. |+|:-------------------------------| ----: | ----: | ----: | ----: | ----: | ----: | ----: | ----: | -----: | ----: | -----------: | ----: |+| **Qwen3-8B**BF16 | 55.46 | 83.38 | 86.73 | 57.04 | 64.00 | 72.96 | 31.20 | 76.61 | 36.72 | 68.27 | 87.57 | 65.45 |+| RTN | 49.23 | 76.30 | 85.63 | 51.93 | 58.45 | 66.18 | 27.40 | 73.12 | 33.29 | 64.48 | 79.98 | 60.54 |+| OPT-RTN(-2,-1,1,2) | 50.17 | 79.25 | 84.98 | 53.18 | 60.20 | 66.88 | 28.80 | 73.83 | 34.88 | 65.43 | 82.03 | 61.78 |+| OPT-RTN(-1,1) (Our's default) | 49.83 | 79.04 | 85.54 | 53.02 | 60.00 | 67.26 | 28.60 | 73.67 | 35.01 | 63.77 | 82.94 | 61.70 |+| | | | | | | | | | | | | |+| **Llama3.1-8B-I** BF16 | 51.54 | 81.78 | 84.04 | 59.13 | 73.14 | 67.96 | 33.00 | 80.03 | 37.21 | 73.80 | 75.28 | 65.17 |+| orig-RTN | 46.08 | 76.64 | 80.37 | 55.60 | 61.42 | 57.11 | 32.00 | 75.52 | 28.15 | 69.69 | 46.70 | 57.21 |+| OPT-RTN(-2,-1,1,2) | 45.48 | 77.78 | 80.83 | 56.10 | 64.62 | 58.81 | 32.40 | 76.44 | 29.01 | 69.69 | 52.08 | 58.48 |+| OPT-RNT(-1,1) (Our's default) | 46.25 | 76.39 | 80.86 | 55.88 | 65.17 | 58.77 | 33.60 | 77.64 | 30.48 | 70.56 | 54.89 | 59.14 |++NVFP4++| Model | ARC-c | ARC-e | BoolQ | Hella | LAMB | MMLU | OBQA | PIQA | Truth. | Wino | GSM8K strict | AVG. |+| :---------------- | -----: | -----: | -----: | -----: | -----: | -----: | -----: | -----: | -----: | -----: | -----------: | ----: |+| **Qwen3-8B** | 55.46 | 83.38 | 86.73 | 57.04 | 64.00 | 72.96 | 31.20 | 76.61 | 36.72 | 68.27 | 87.57 | 65.45 |+| RTN | 54.35 | 81.65 | 86.02 | 55.36 | 62.31 | 70.93 | 30.20 | 75.79 | 34.76 | 68.59 | 84.15 | 64.01 |+| opt-rtn | 54.69 | 82.24 | 85.72 | 55.09 | 63.77 | 71.33 | 31.60 | 75.52 | 35.74 | 66.30 | 86.35 | 64.40 |+| | | | | | | | | | | | | |+| **Llama3.1-8B-I** | 51.54 | 81.78 | 84.04 | 59.13 | 73.14 | 67.96 | 33.00 | 80.03 | 37.21 | 73.80 | 75.28 | 65.17 |+| RTN | 49.15 | 79.25 | 83.24 | 58.29 | 71.20 | 64.05 | 35.00 | 78.62 | 33.41 | 72.85 | 64.06 | 62.65 |+| opt-rtn | 51.02 | 80.13 | 84.53 | 58.40 | 71.34 | 64.76 | 35.60 | 79.43 | 35.62 | 72.93 | 69.29 | 63.91 |++### 🧮 Evaluation Results (LM-Eval)For 2/3bit, we strongly recommend not using iter=0 except for GGUF:Q2_K_S which has a different quantization algorithm.