Skip to content

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

refine xpu requirement/config json and fix several issues (#558)

Wenhua Chenga45eadb3284e
diff --git a/README.md b/README.md
index dffcd2135..ba7e50a16 100644
--- a/README.md
+++ b/README.md
@@ -45,12 +45,9 @@ and [fbaldassarri](https://huggingface.co/fbaldassarri).
### Install from pypi
```bash
-# GPU
+# CPU/Intel GPU/CUDA
pip install auto-round
-# CPU
-pip install auto-round[cpu]
-
# HPU
pip install auto-round-lib
```
@@ -59,12 +56,9 @@ pip install auto-round-lib
<summary>Build from Source</summary>
```bash
- # GPU
+ # CPU/Intel GPU/CUDA
pip install .
- # CPU
- pip install .[cpu]
-
# HPU
python setup.py install lib
```
@@ -89,7 +83,8 @@ auto-round \
--output_dir ./tmp_autoround
```
-We offer two configurations, `auto-round-best` and `auto-round-light`, designed for optimal accuracy and improved speed,
+We offer another two configurations, `auto-round-best` and `auto-round-light`,
+designed for optimal accuracy and improved speed,
respectively. Details are as follows.
<details>
<summary>Other Recipes</summary>
diff --git a/auto_round/autoround.py b/auto_round/autoround.py
index f63827cf7..12577a29a 100644
--- a/auto_round/autoround.py
+++ b/auto_round/autoround.py
@@ -51,7 +51,7 @@ from .utils import (
set_module,
llm_load_model,
reset_params,
- init_cache, check_skippable_keywords, get_shared_keys,
+ init_cache, check_skippable_keywords, get_shared_keys, supported_dtypes, infer_bits_by_data_type,
)
from .low_cpu_mem.utils import get_layers_before_block
@@ -182,6 +182,7 @@ class AutoRound(object):
self.enable_norm_bias_tuning = enable_norm_bias_tuning
self.group_size = group_size
self.sym = sym
+
self.low_gpu_mem_usage = low_gpu_mem_usage
self.low_cpu_mem_usage = low_cpu_mem_usage
self.layer_config = {} if layer_config is None else layer_config
@@ -200,6 +201,11 @@ class AutoRound(object):
self.minmax_lr = minmax_lr or self.lr
self.data_type = data_type
+ tmp_bits = infer_bits_by_data_type(self.data_type)
+ if tmp_bits<16 and tmp_bits!=bits:
+ logger.warning(
+ f"bits set in 'data_type' do not match the specified 'bits' setting. Resetting 'bits' to {tmp_bits}.")
+ self.bits = tmp_bits
self.supported_types = supported_layer_types
self.model = model.eval()
self.tokenizer = tokenizer
@@ -217,7 +223,17 @@ class AutoRound(object):
self.act_bits = act_bits if not (act_bits is None) else self.bits
self.act_sym = act_sym if not (act_sym is None) else self.sym
self.act_dynamic = act_dynamic
- self.act_data_type = act_data_type if act_data_type is not None else data_type
+ self.act_data_type = act_data_type
+ if self.act_data_type is None:
+ if data_type in supported_dtypes and self.act_bits <= 16:
+ self.act_data_type = data_type
+ logger.info(f"activation adopts {data_type}")
+ else:
+ self.act_data_type = "float"
+
+ tmp_act_bits = infer_bits_by_data_type(self.act_data_type)
+ if tmp_act_bits < 16:
+ self.act_bits = tmp_act_bits
self.sampler = sampler
self.not_use_best_mse = not_use_best_mse
@@ -532,13 +548,18 @@ class AutoRound(object):
m = WrapperLinear(m, enable_minmax_tuning=False, enable_norm_bias_tuning=False, enable_round_tuning=False)
m = m.unwrapper({})
m.to("cpu")
+ if self.low_gpu_mem_usage:
+ clear_memory()
if self.is_packing_immediate:
from auto_round.export import PACKING_LAYER_WITH_FORMAT
if check_to_quantized(m):
target_backend = self.formats[0].split(":")[0] if ":" in self.formats[0] else self.formats[0]
- PACKING_LAYER_WITH_FORMAT[target_backend](n, self.model, self.formats[0])
+ PACKING_LAYER_WITH_FORMAT[target_backend](name, self.model, self.formats[0])
+ if self.low_gpu_mem_usage:
+ clear_memory()
else:
set_module(self.model, name, m)
+
self.quantized = True
return self.model, self.layer_config
@@ -1604,7 +1625,7 @@ class AutoRound(object):
"""
# only support to export afp8
if self.act_bits <= 8:
- if "fp8" not in self.act_data_type:
+ if "fp8" not in self.act_data_type or self.act_dynamic:
if format != "fake":
logger.warning(
f"Currently only support to export auto_round format quantized model"
@@ -1615,7 +1636,7 @@ class AutoRound(object):
else:
if format != "auto_round":
logger.warning(
- f"Currently only support to export auto_round format for W{self.bits}AFP8 model,"
+ f"Currently only support to export auto_round format for static W{self.bits}AFP8 model,"
" change format to auto_round"
)
format = "auto_round"
@@ -1806,7 +1827,7 @@ class AutoRound(object):
@classmethod
@torch.no_grad()
def sampling_inputs(cls, input_ids, input_others, indices, seqlen,
- batch_dim=0,share_cache_keys=()):
+ batch_dim=0, share_cache_keys=()):
"""Samples inputs based on the given indices and sequence length.
Args:
diff --git a/auto_round/data_type/nvfp.py b/auto_round/data_type/nvfp.py
new file mode 100644
index 000000000..2a93e62d5
--- /dev/null
+++ b/auto_round/data_type/nvfp.py
@@ -0,0 +1,79 @@
+# Copyright (c) 2025 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.
+
+import torch
+
+from auto_round.data_type.fp8 import float8_e4m3fn_ste
+from auto_round.data_type.register import register_dtype
+from auto_round.data_type.utils import reshape_pad_tensor_by_group_size, revert_tensor_by_pad
+
+
+# taken from
+# https://github.com/vllm-project/vllm/blob/ebb554cdb7cd9cc54b2feec20c45ab9cd9067d52/tests/kernels/test_nvfp4_quant.py
+def cast_to_fp4(x):
+ sign = torch.sign(x)
+ x = torch.abs(x)
+ x[(x >= 0.0) & (x <= 0.25)] = 0.0
+ x[(x > 0.25) & (x < 0.75)] = 0.5
+ x[(x >= 0.75) & (x <= 1.25)] = 1.0
+ x[(x > 1.25) & (x < 1.75)] = 1.5
+ x[(x >= 1.75) & (x <= 2.5)] = 2.0
+ x[(x > 2.5) & (x < 3.5)] = 3.0
+ x[(x >= 3.5) & (x <= 5.0)] = 4.0
+ x[x > 5.0] = 6.0
+ return x * sign
+
+
+def cast_to_fp4_ste(x):
+ fp4 = (cast_to_fp4(x).to(x.dtype) - x).detach() + x
+
+ return fp4
+
+
+def get_reciprocal(x):
+ if isinstance(x, torch.Tensor):
+ return torch.where(x == 0, torch.tensor(0.0, dtype=x.dtype), 1.0 / x)
+ elif isinstance(x, (float, int)):
+ return 0.0 if x == 0 else 1.0 / x
+ else:
+ raise TypeError("Input must be a float, int, or a torch.Tensor.")
+
+
+FLOAT4_E2M1_MAX = 6.0
+FLOAT8_E4M3_MAX = torch.finfo(torch.float8_e4m3fn).max
+
+
+def ref_nvfp4_quant(x, global_scale, block_size=16, v=0):
+ assert global_scale.dtype == torch.float32
+ assert x.ndim == 2
+ m, n = x.shape
+ vec_max = torch.max(torch.abs(x), dim=-1, keepdim=True)[0].to(torch.float32)
+ scale = global_scale * (vec_max * get_reciprocal(FLOAT4_E2M1_MAX))
+ scale = float8_e4m3fn_ste(scale).to(torch.float32)
+ output_scale = get_reciprocal(scale * get_reciprocal(global_scale))
+
+ scaled_x = x.to(torch.float32) * output_scale
+ clipped_x = torch.clamp(scaled_x, -6.0, 6.0) + v
+ return (cast_to_fp4_ste(clipped_x) * get_reciprocal(output_scale)).reshape(m, n), output_scale
+
+
+@register_dtype("nv_fp4")
+def full_quant(tensor, bits=4, group_size=16, v=0, **kwargs):
+ orig_dtype = tensor.dtype
+ tensor, orig_shape, pad_len = reshape_pad_tensor_by_group_size(tensor, group_size)
+ tensor_amax = tensor.abs().max().to(torch.float32)
+ global_scale = FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX / tensor_amax
+ qdq_res, output_scale = ref_nvfp4_quant(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), output_scale, None
diff --git a/auto_round/export/export_to_autogptq/export.py b/auto_round/export/export_to_autogptq/export.py
index 65f9088bf..3285f4761 100644
--- a/auto_round/export/export_to_autogptq/export.py
+++ b/auto_round/export/export_to_autogptq/export.py
@@ -37,7 +37,7 @@ import torch
import auto_round.export.export_to_autogptq.qlinear_triton
from auto_round.utils import check_to_quantized, get_block_names, \
- get_module, logger, set_module, supported_layer_types
+ get_module, logger, set_module, supported_layer_types, filter_quantization_config
import copy
import json
import os
@@ -193,6 +193,7 @@ def save_quantized_as_autogptq(output_dir, inplace=True, backend="auto_gptq:exll
quantization_config["damp_percent"] = 0.01
if modules_in_block_to_quantize is not None:
quantization_config["modules_in_block_to_quantize"] = modules_in_block_to_quantize
+ filter_quantization_config(quantization_config)
if hasattr(model, "config"):
model.config.quantization_config = quantization_config
diff --git a/auto_round/export/export_to_autoround/export.py b/auto_round/export/export_to_autoround/export.py
index bf48eb05d..02ead0464 100644
--- a/auto_round/export/export_to_autoround/export.py
+++ b/auto_round/export/export_to_autoround/export.py
@@ -24,7 +24,8 @@ import transformers
import auto_round.export.export_to_autoround.qlinear_triton_act
import auto_round_extension.cuda.qlinear_tritonv2
-from auto_round.utils import get_module, logger, set_module, supported_layer_types, check_to_quantized
+from auto_round.utils import get_module, logger, set_module, supported_layer_types, check_to_quantized, \
+ filter_quantization_config
import threadpoolctl as tctl
import inspect
from tqdm import tqdm
@@ -306,7 +307,7 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:ex
for _ in executor.map(wrapper, names):
pass
-
+ filter_quantization_config(quantization_config)
if hasattr(model, "config"):
model.config.quantization_config = quantization_config
if output_dir is None:
@@ -324,6 +325,8 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:ex
processor.save_pretrained(output_dir)
if quantization_config.get("act_bits", 16) <= 8:
dtype = torch.bfloat16
+ elif "awq" in quantization_config.get("packing_format", "auto_round:auto_gptq"):
+ dtype = torch.float16 ## awq kernel only supports float16 on cuda
else:
dtype = None
save(model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
@@ -364,4 +367,3 @@ def save(model: nn.Module, save_dir: str, max_shard_size: str = "5GB", safe_seri
if hasattr(model, "config") and hasattr(model.config, "quantization_config"):
with open(os.path.join(save_dir, config_file), "w", encoding="utf-8") as f:
json.dump(model.config.quantization_config, f, indent=2)
-
diff --git a/auto_round/export/export_to_awq/export.py b/auto_round/export/export_to_awq/export.py
index 6cfe53778..729db0439 100644
--- a/auto_round/export/export_to_awq/export.py
+++ b/auto_round/export/export_to_awq/export.py
@@ -28,7 +28,7 @@ from auto_round.utils import (logger, get_module,
set_module,
check_to_quantized,
get_block_names,
- extract_block_names_to_str, supported_layer_types)
+ extract_block_names_to_str, supported_layer_types, filter_quantization_config)
import copy
import json
from .utils import WQLinear_GEMM
@@ -135,7 +135,7 @@ def save_quantized_as_autoawq(output_dir, inplace=True, **kwargs):
quantization_config["modules_to_not_convert"] = modules_to_not_convert
##check module quantized in block, this may have bug for mixed precision quantization
-
+ filter_quantization_config(quantization_config)
if hasattr(compressed_model, "config"):
compressed_model.config.quantization_config = quantization_config
safe_serialization = kwargs.get('safe_serialization', True)
diff --git a/auto_round/inference/auto_quantizer.py b/auto_round/inference/auto_quantizer.py
index dda3b3fc4..49f195ee9 100644
--- a/auto_round/inference/auto_quantizer.py
+++ b/auto_round/inference/auto_quantizer.py
@@ -314,9 +314,7 @@ class AutoRoundQuantizer(HfQuantizer):
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
if torch_dtype is None:
- torch_dtype = torch.float16
- elif torch_dtype != torch.float16:
- logger.info("We suggest you to set `torch_dtype=torch.float16` for better efficiency on CUDA")
+ torch_dtype = torch.bfloat16
return torch_dtype
def post_init_model(self, model):
diff --git a/auto_round/inference/backend.py b/auto_round/inference/backend.py
index 7fd935d21..53d99ada0 100644
--- a/auto_round/inference/backend.py
+++ b/auto_round/inference/backend.py
@@ -13,6 +13,7 @@
# limitations under the License.
import functools
+import logging
from dataclasses import dataclass, field
from typing import List, Any, Optional
@@ -203,15 +204,17 @@ BackendInfos['qbits_zp'] = BackendInfo(device=["cpu"], sym=[True, False],
feature_checks=[],
alias=["itrex", "qbits"],
convertable_format=["int32_zp"],
- requirements=["intel-extension-for-transformers","torch<2.7.0"]
+ requirements=["intel-extension-for-transformers", "torch<2.7.0"]
)
BackendInfos['auto_round:qbits_awq'] = BackendInfo(device=["cpu"], sym=[True, False], ## for awq, not robust
packing_format="awq",
bits=[2, 4, 8], group_size=None,
+ dtype=["float16", "bfloat16"],
priority=0,
feature_checks=[],
- requirements=["intel-extension-for-transformers"]
+ alias=["itrex", "qbits"],
+ requirements=["intel-extension-for-transformers", "torch<2.7.0"]
)
BackendInfos['ipex_gptq'] = BackendInfo(device=["cpu", "xpu"], sym=[True, False],
@@ -623,20 +626,7 @@ def get_layer_backend(device, backend, orig_backend, bits, group_size, sym, in_f
key=lambda support_backend: BackendInfos[support_backend].priority,
reverse=True)
backend_info = BackendInfos[supported_backends_need_package[0]]
- logger.error("please install all the following packages to support inference")
- for requirement in backend_info.requirements:
- if isinstance(requirement, str):
- try:
- require_version(requirement)
- except ImportError:
- if "gptqmodel" in requirement:
- logger.error(f"pip install -v '{requirement}' --no-build-isolation")
- else:
- logger.error(f"pip install '{requirement}' ")
- else:
- str_info = requirement()[1]
- logger.error(str_info)
- exit(-1)
+ process_requirement(backend_info.requirements, target_device=device)
return None
@@ -684,30 +674,64 @@ def get_highest_priority_backend(bits, sym, group_size, device, packing_format):
return None
-def process_requirement(requirements: list):
- gptqmodel_requirements = None
- other_requirements = []
- for requirement in requirements:
- try:
- require_version(requirement)
- except:
- if "gptqmodel" in requirement:
- gptqmodel_requirements = requirement
- else:
- other_requirements.append(requirement)
+def process_requirement(requirements: list, target_device="cuda", logger_level="error"):
+ def log(message):
+ (logger.warning if logger_level != "error" else logger.error)(message)
+
+ def build_pip_commands(gptq_req, other_reqs):
+ commands = []
+
+ if gptq_req:
+ commands.append(f"pip install -v '{gptq_req}' --no-build-isolation")
+ try:
+ require_version("numpy<2.0")
+ except:
+ commands.append("pip install 'numpy<2.0'")
+
+ if other_reqs:
+ other_str = " ".join(other_reqs)
+ commands.append(f"pip install {other_str}")
- infos = []
+ return commands
- if gptqmodel_requirements is not None:
- infos.append(f"pip install -v '{gptqmodel_requirements}' --no-build-isolation")
+ # Filter requirements
+ missing_requirements = []
+ for req in requirements:
try:
- require_version("numpy<2.0")
+ require_version(req)
except:
- infos.append(f"pip install 'numpy<2.0'")
-
- other_info = f"pip install"
- if len(other_requirements) > 0:
- for requirement in other_requirements:
- other_info += f" {requirement}"
- infos.append(other_info)
- return infos
+ missing_requirements.append(req)
+
+ gptq_req = next((req for req in missing_requirements if "gptqmodel" in req), None)
+ other_reqs = [req for req in missing_requirements if "gptqmodel" not in req]
+
+ pip_cmds = build_pip_commands(gptq_req, other_reqs)
+ if not pip_cmds:
+ return
+
+ # Instructional messages
+ install_instructions = []
+ for cmd in pip_cmds:
+ if "intel-extension-for-pytorch" in cmd and target_device == "xpu":
+ install_instructions.append(
+ "Please refer to https://pytorch-extension.intel.com/installation?platform=gpu "
+ "to install intel-extension-for-pytorch. Ensure that the version matches your installed PyTorch."
+ )
+
+ prefix_msg = (
+ "Better backend is found, please install all the following requirements to enable it."
+ if logger_level != "error"
+ else "Inference requires the following libraries. Please install all of them."
+ )
+ log(prefix_msg)
+
+ for msg in install_instructions:
+ log(msg)
+ if logger_level == "error" and len(pip_cmds) == 0:
+ exit(-1)
+
+ joined_cmds = " and ".join(f"`{cmd}`" for cmd in pip_cmds)
+ if joined_cmds:
+ log(joined_cmds)
+ if logger_level == "error":
+ exit(-1)
diff --git a/auto_round/inference/convert_model.py b/auto_round/inference/convert_model.py
index 85e4c06cf..48d2bec11 100644
--- a/auto_round/inference/convert_model.py
+++ b/auto_round/inference/convert_model.py
@@ -227,7 +227,7 @@ def get_layer_config(model, quantization_config):
# Determine the quantization block list
quant_block_list = getattr(quantization_config, "quant_block_list", None)
if quant_block_list is None:
- to_quant_block_names = getattr(quantization_config, "block_name_to_quantize", None) # Prioritize this parameter
+ to_quant_block_names = getattr(quantization_config, "block_name_to_quantize", None) # Prioritize this parameter
if to_quant_block_names is None:
to_quant_block_names = getattr(quantization_config, "to_quant_block_names", None)
if isinstance(to_quant_block_names, (list, tuple)):
@@ -314,14 +314,7 @@ def _replace_by_quant_layers(module: nn.Module, layer_configs, target_backend, t
raise ValueError(f"{target_backend} does not support {target_device}, please change device or backend")
##check requirements
requirements = BackendInfos[layer_backend_must].requirements
- requirements_info = process_requirement(requirements)
- if len(requirements_info) > 0:
- extra_info = ""
- for index, req in enumerate(requirements_info):
- extra_info += (f"`{req}`")
- if index != len(requirements_info) - 1:
- extra_info += " and "
- raise ImportError(f"{target_backend} requires the follow libraries. Please install them via {extra_info}")
+ process_requirement(requirements, target_device)
target_backend = target_backend or orig_backend # Default to original backend if not specified
@@ -431,7 +424,6 @@ def infer_target_device(device_map=None):
target_device = str(device).split(":")[0]
else:
target_device = get_available_devices()[0]
- assert isinstance(target_device, str)
return target_device
@@ -554,16 +546,7 @@ def convert_hf_model(model: nn.Module, target_device="cpu"):
quantization_config.group_size, target_device,
BackendInfos[orig_backend].packing_format)
if best_backend is not None and best_backend not in used_backends:
- info = f"better backend is found, please install all the following requirements to enable it,"
- extra_info = info
requirements = BackendInfos[best_backend].requirements
- requirements_info = process_requirement(requirements)
- for index, req in enumerate(requirements_info):
- extra_info += (f"`{req}`")
- if index != len(requirements_info) - 1:
- extra_info += " and "
-
- logger.warning(extra_info)
+ process_requirement(requirements, target_device,"warning")
return model, used_backends
-
diff --git a/auto_round/utils.py b/auto_round/utils.py
index 394bfc10e..cbe7ae22d 100644
--- a/auto_round/utils.py
+++ b/auto_round/utils.py
@@ -42,6 +42,20 @@ supported_formats = supported_formats + tuple(GGUF_CONFIG.keys())
supported_layer_types = (torch.nn.Linear, transformers.modeling_utils.Conv1D)
+supported_dtypes = ("int", "mx_fp", "fp", "nv_fp")
+
+
+def infer_bits_by_data_type(data_type: str):
+ for supported_dtype in supported_dtypes:
+ if data_type.startswith(supported_dtype) and len(data_type) > len(supported_dtype):
+ ##first check the following two bits
+ suc_2str = data_type[len(supported_dtype):len(supported_dtype) + 2]
+ if str.isdigit(suc_2str):
+ return int(suc_2str)
+ if str.isdigit(data_type[len(supported_dtype)]):
+ return int(data_type[len(supported_dtype)])
+ return 16
+
@lru_cache(None)
def warning_once(self, msg: str):
@@ -292,44 +306,6 @@ def check_is_cpu(device):
return device == torch.device("cpu") or device == "cpu"
-def validate_modules(module_names, quant_vision=False, vison_blocks_names=None):
- """
- Test a list of modules' validity.
-
- Args:
- modules (list of str): List of strings to be validated.
-
- Returns:
- bool: True if all modules have equal length or not dependent, otherwise False.
- """
- if not bool(module_names): # pragma: no cover
- raise ValueError(f"Empty modules")
- if len(module_names) < 2:
- return True
- split_modules = [s.split('.') for s, _ in module_names]
- lengths = [len(parts) for parts in split_modules]
- if len(set(lengths)) == 1: # pragma: no cover
- return True
- max_length = max(lengths)
- min_length = min(lengths)
- longest_module = next(s for s in split_modules if len(s) == max_length)
- shortest_module = next(s for s in split_modules if len(s) == min_length)
- shortest_module = '.'.join(shortest_module)
- longest_module = '.'.join(longest_module)
- # Check if the shortest name is a substring of the longest name
- if shortest_module in longest_module: # pragma: no cover
- raise ValueError(f"Invalid modules, at least two modules detected" \
- " as dependent, {shortest_module} and {longest_module}")
- flag = False
- if quant_vision:
- for n, _ in module_names:
- flag = any(key not in n.lower() for key in (vison_blocks_names))
- if quant_vision and not flag:
- raise ValueError(f"Cannot find the visual block. Please reset the quant_nontext_module parameter to False, " \
- "or raise an issue at https://github.com/intel/auto-round/issues.")
- return
-
-
def get_common_prefix(paths):
# Split each path into components and find the common prefix
split_paths = [path.split('.') for path in paths]
@@ -1460,4 +1436,29 @@ def get_model_dtype(model_dtype, default="auto"):
else:
logger.warning(f"Unable to identify model_dtype {model_dtype}, reset to default model_dtype {default}")
model_dtype = default
- return model_dtype
\ No newline at end of file
+ return model_dtype
+
+
+def filter_quantization_config(quantization_config):
+ default_dict = {"amp": True, "batch_size": 8, "data_type": int, "dataset": "NeelNanda/pile-10k",
+ "enable_minmax_tuning": True, "enable_norm_bias_tuning": False, "enable_quanted_input": True,
+ "gradient_accumulate_steps": 1, "iters": 200, "low_gpu_mem_usage": False, "nsamples": 128,
+ "scale_dtype": "torch.float16", "seqlen": 2048}
+ iters = quantization_config.get("iters", 200)
+
+ default_dict["lr"] = 1.0 / iters if iters > 0 else 5e-3
+ default_dict["minmax_lr"] = default_dict["lr"]
+
+ for key in default_dict:
+ if key in quantization_config and default_dict[key] == quantization_config[key]:
+ quantization_config.pop(key)
+ for k in list(quantization_config.keys()):
+ if quantization_config[k] is None:
+ quantization_config.pop(k)
+
+ if quantization_config.get("act_bits", 16) >= 16:
+ quantization_config.pop("act_bits", None)
+ quantization_config.pop("act_data_type", None)
+ quantization_config.pop("act_dynamic", None)
+ quantization_config.pop("act_sym", None)
+ quantization_config.pop("act_group_size", None)
diff --git a/auto_round/wrapper.py b/auto_round/wrapper.py
index a624d9f21..3d787c128 100644
--- a/auto_round/wrapper.py
+++ b/auto_round/wrapper.py
@@ -75,24 +75,12 @@ class WrapperLinear(torch.nn.Module):
self.enable_minmax_tuning = enable_minmax_tuning
self.enable_round_tuning = enable_round_tuning
self.enable_norm_bias_tuning = enable_norm_bias_tuning and (orig_layer.bias is not None)
- self.enable_act_quant = self.orig_layer.act_bits <= 8 or self._check_act_quantization(
- self.orig_layer.act_data_type)
+ self.enable_act_quant = self.orig_layer.act_bits <= 8
self.q_scale_thresh = 1e-5
self._init_tuning_params_and_quant_func()
self.orig_forward = self.linear_forward if isinstance(self.orig_layer, torch.nn.Linear) else self.conv1d_forward
- @staticmethod
- def _check_act_quantization(data_type: str):
- support_dtypes = ["int", "mx_fp", "fp", "nv_fp"]
- for support_dtype in support_dtypes:
- if data_type.startswith(support_dtype) and len(data_type) > len(support_dtype):
- ##first check the following two bits
- suc_2str = data_type[len(support_dtype):len(support_dtype) + 2]
- if str.isdigit(suc_2str): ##>8
- return False
- if str.isdigit(data_type[len(support_dtype)]) and int(data_type[len(support_dtype)]) <= 8:
- return True
- return False
+
def _init_tuning_params_and_quant_func(self):
"""Initializes tuning parameters and quantization functions.
diff --git a/docs/step_by_step.md b/docs/step_by_step.md
index 2be872828..b7e6aab49 100644
--- a/docs/step_by_step.md
+++ b/docs/step_by_step.md
@@ -83,7 +83,7 @@ AutoRound supports several quantization configurations:
### Hardware Compatibility
-CPU, Intel GPU, HPU,and CUDA for both quantization and inference.
+CPU, Intel GPU, HPU and CUDA for both quantization and inference.
### Command Line Usage
@@ -267,9 +267,73 @@ output_dir = "./tmp_autoround"
autoround.quantize_and_save(output_dir, format='gguf:q4_0') # gguf:q4_1
```
+### Device/Multi-GPU setting in Quantization
+**The tuning device is specified using the `device` argument in AutoRound API, _not_ through the `device_map`
+parameter used by Transformers.from_pretrained.**
+
+
+There are typically two scenarios that require multi-GPU tuning: one is the calibration phase during LM head quantization, and the other is quantizing extremely large models (e.g., models larger than 100 GB).
+
+#### Enable multiple gpus calibration in lm_head quantization
+For LM head tuning, AutoRound needs to cache the inputs to the lm-head, which requires the entire model to reside on
+ the GPU for efficient calibration. If the model is too large to fit into a single GPU, AutoRound will prompt the user to use `--device '0,1'` to load the model across multiple GPUs.
+
+#### Enable multiple gpus tuning for extremely large model
+AutoRound tunes the model in a block-by-block manner. Although the block size is much smaller than the model size, it still requires a significant amount of GPU memory for tuning—typically 10 times the block size. This can lead to out-of-memory (OOM) errors when working with extremely large models.
+
+For strategies to reduce GPU memory usage, please refer to the [Reduced GPU Memory Usage](###Adjust Hyperparameters)
+section below, where you
+can adjust hyperparameters to optimize memory consumption.
+
+If adjusting hyperparameters does not resolve the issue, we also support mapping different layers within a block to
+different devices by setting the `device_map` argument in the AutoRound API. For reference, we provide an example of
+quantizing the DeepSeekV3-BF16 (1.4T) model using five 80GB GPUs.
+~~~python
+import torch
+from transformers import AutoModelForCausalLM, AutoTokenizer
+model_name = "opensourcerelease/DeepSeek-R1-bf16"
+
+tokenizer = AutoTokenizer.from_pretrained(model_name)
+model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True, torch_dtype="auto")
+
+block = model.model.layers
+device_map = {}
+
+for n, m in block.named_modules():
+ if isinstance(m, (torch.nn.Linear)):
+ if "experts" in n and ("shared_experts" not in n) and int(n.split('.')[-2]) < 63:
+ device = "cuda:1"
+ elif "experts" in n and ("shared_experts" not in n) and int(n.split('.')[-2]) >= 63 and int(
+ n.split('.')[-2]) < 128:
+ device = "cuda:2"
+ elif "experts" in n and ("shared_experts" not in n) and int(n.split('.')[-2]) >= 128 and int(
+ n.split('.')[-2]) < 192:
+ device = "cuda:3"
+ elif "experts" in n and ("shared_experts" not in n) and int(
+ n.split('.')[-2]) >= 192:
+ device = "cuda:4"
+ else:
+ device = "cuda:0"
+ n = n[2:]
+
+ device_map.update({n: device})
+
+from auto_round import AutoRound
+
+autoround = AutoRound(model=model, tokenizer=tokenizer, device_map=device_map, nsamples=512,
+ batch_size=4, low_gpu_mem_usage=True, seqlen=2048,
+ )
+autoround.quantize()
+autoround.save_quantized(format="auto_awq", output_dir="tmp_autoround")
+~~~
+
+
+
### Adjust Hyperparameters
- **Reduced GPU Memory Usage:**
+
+ - set `enable_torch_compile` to True
- enable `low_gpu_mem_usage`(more tuning cost)
@@ -297,6 +361,8 @@ autoround.quantize_and_save(output_dir, format='gguf:q4_0') # gguf:q4_1
- **Speedup the tuning:**
+ - set `enable_torch_compile` to True
+
- use `auto-round-light` configuration
- reduce the seqlen to 512(potential large accuracy drop for some scenarios)
diff --git a/test/test_act_quantization.py b/test/test_act_quantization.py
index a4ada07dc..57fde6396 100644
--- a/test/test_act_quantization.py
+++ b/test/test_act_quantization.py
@@ -48,7 +48,7 @@ class TestAutoRoundAct(unittest.TestCase):
seqlen=2,
dataset=self.llm_dataloader,
act_bits=4,
- data_type="mx_fp4"
+ data_type="mx_fp"
)
autoround.quantize()
diff --git a/test/test_block_names.py b/test/test_block_names.py
index 7c618b685..e1e70742e 100644
--- a/test/test_block_names.py
+++ b/test/test_block_names.py
@@ -144,9 +144,8 @@ class TestQuantizationBlocks(unittest.TestCase):
def test_block_name_quant(self):
self.model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
- from auto_round.utils import get_block_names, validate_modules
+ from auto_round.utils import get_block_names
llm_block_names = get_block_names(self.model)
- validate_modules(llm_block_names)
bits, group_size, sym, batch_size = 4, 128, True, 20
autoround = AutoRound(
self.model,