Skip to content

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

add support for scheme FP8_STATIC to export llm_compressor format (#816)

Heng Guo1089004a4f70
diff --git a/auto_round/compressors/base.py b/auto_round/compressors/base.py
index 9ed346bb8..e9e0a66af 100644
--- a/auto_round/compressors/base.py
+++ b/auto_round/compressors/base.py
@@ -865,9 +865,9 @@ class BaseCompressor(object):
elif is_nv_fp(self.data_type) or is_mx_fp(self.data_type):
format = f"auto_round:{self.data_type}"
elif is_static_wfp8afp8(self): # staic wfp8afp8
- format = f"auto_round:{AutoRoundFormat.TORCH_FP8_STATIC.value}"
+ format = f"auto_round:{AutoRoundFormat.FP8_STATIC.value}"
elif self.data_type == "fp" and self.bits == 8 and self.act_bits >= 16: # woq fp8
- format = "auto_round:fp8"
+ format = f"auto_round:{AutoRoundFormat.FP8.value}"
elif self.act_bits < 16:
raise ValueError(
"AutoRound format does not support exporting "
@@ -882,6 +882,20 @@ class BaseCompressor(object):
check_compressed_tensors_supported()
format = format.replace("llm_compressor", f"llm_compressor:{self.data_type}")
formats[index] = format
+ if is_static_wfp8afp8(self):
+ format = f"llm_compressor:{AutoRoundFormat.FP8_STATIC.value}"
+ formats[index] = format
+ if self.act_group_size != 0:
+ logger.warning(
+ f"scheme FP8_STATIC export to llm_compressor format only support for act_group_size 0,"
+ f" ,but got act_group_size={self.act_group_size}, reset = 0"
+ )
+ self.act_group_size = 0
+ if self.group_size > 0:
+ logger.warning(
+ f"please note that group_size={self.group_size}"
+ " may not be supported for llm_compressor format, and cannot be loaded in llm_compressor"
+ )
elif not is_wfp8afp8(self):
logger.error(
"Currently, the llm_compressor format only supports MXFP/NVFP/FP8. "
@@ -971,13 +985,25 @@ class BaseCompressor(object):
)
format = "fake"
else:
- if not (format == "auto_round" or format == f"auto_round:{AutoRoundFormat.TORCH_FP8_STATIC.value}"):
+ if format not in [
+ "auto_round",
+ f"auto_round:{AutoRoundFormat.FP8_STATIC.value}",
+ f"llm_compressor:{AutoRoundFormat.FP8_STATIC.value}",
+ "auto_round:llm_compressor",
+ ]:
logger.warning(
f"Currently only support to export auto_round or fake format for static W{self.bits}AFP8 model,"
f" change format {format} to auto_round"
)
- format = "auto_round"
- if self.act_group_size != 0 and not self.act_dynamic and format == "auto_round:fp8":
+ if is_static_wfp8afp8(self):
+ format = f"auto_round:{AutoRoundFormat.FP8_STATIC.value}"
+ else:
+ format = f"auto_round:{AutoRoundFormat.FP8.value}"
+ if (
+ self.act_group_size != 0
+ and not self.act_dynamic
+ and format == f"auto_round:{AutoRoundFormat.FP8.value}"
+ ):
logger.warning(
f"Please note that quantize activation with act_group_size={self.act_group_size}"
" may result in failure to export or import normally."
@@ -1198,7 +1224,7 @@ class BaseCompressor(object):
def get_imatrix_hook(module, input, output):
input = input[0] if isinstance(input, (tuple, list)) else input
flattened = input.reshape(-1, input.shape[-1]).to(torch.float32)
- squared = torch.sum(flattened**2, dim=0).to(torch.float32)
+ squared = torch.sum(torch.pow(flattened, 2), dim=0).to(torch.float32)
if not hasattr(module, "imatrix"):
module.imatrix = squared
@@ -3094,6 +3120,8 @@ class BaseCompressor(object):
)
if format == "llm_compressor" and (is_nv_fp(self.data_type) or is_mx_fp(self.data_type)):
format = format.replace("llm_compressor", f"llm_compressor:{self.data_type}")
+ if format == "llm_compressor" and is_static_wfp8afp8(self):
+ format = format.replace("llm_compressor", "llm_compressor:{AutoRoundFormat.FP8_STATIC.value}")
from auto_round.export import EXPORT_FORMAT
diff --git a/auto_round/data_type/gguf.py b/auto_round/data_type/gguf.py
index 26c262ba1..6456b817f 100644
--- a/auto_round/data_type/gguf.py
+++ b/auto_round/data_type/gguf.py
@@ -337,7 +337,7 @@ def quant_tensor_gguf_asym_dq(
if bits == 2:
quant_weights = torch.abs(tensor)
elif bits == 4 or bits == 5:
- sigma2 = torch.sum(tensor**2, dim=-1, keepdim=True) / 32 ##Note 32 is different from QK_K
+ sigma2 = torch.sum(torch.pow(tensor, 2), dim=-1, keepdim=True) / 32 ##Note 32 is different from QK_K
av_x = torch.sqrt(sigma2)
quant_weights = torch.abs(tensor) + av_x
params = search_kwargs[bits]
@@ -384,7 +384,9 @@ def quant_tensor_gguf_asym_dq(
if bits == 2:
tmp_quant_weights = torch.abs(tensor)
elif bits == 4 or bits == 5:
- sigma2 = torch.sum(tensor**2, dim=-1, keepdim=True) / 32 ## Note 32 is different from QK_K
+ sigma2 = (
+ torch.sum(torch.pow(tensor, 2), dim=-1, keepdim=True) / 32
+ ) ## Note 32 is different from QK_K
av_x = torch.sqrt(sigma2)
tmp_quant_weights = torch.abs(tensor) + av_x
quant_weights[replace_index, :] = tmp_quant_weights[replace_index, :]
@@ -395,7 +397,7 @@ def quant_tensor_gguf_asym_dq(
tmp_quant_weights = tmp_quant_weights.view(-1, 1).expand(-1, quant_weights.shape[1])
quant_weights[mean_replace_index, :] = tmp_quant_weights[mean_replace_index, :]
- # sigma2 = torch.sum(tensor ** 2, dim=-1, keepdim=True) / QK_K
+ # sigma2 = torch.sum(torch.pow(tensor, 2), dim=-1, keepdim=True) / QK_K
# if imatrix is None:
# av_x = torch.sqrt(sigma2)
# quant_weights = torch.abs(av_x + tensor * tensor)
@@ -470,7 +472,7 @@ def iterative_wls_quant_search(data, bits=4, rrmin=-1.0, rdelta=0.1, nstep=20, u
quant_data = torch.clamp(torch.round(iscale * (data - rmin)), minq, maxq)
diff = scale * quant_data + rmin - data
- best_mad = torch.sum((weights * torch.abs(diff)) if use_mad else weights * diff**2, dim=1, keepdim=True)
+ best_mad = torch.sum((weights * torch.abs(diff)) if use_mad else weights * torch.pow(diff, 2), dim=1, keepdim=True)
for is_ in range(nstep):
factor = rrmin + rdelta * is_ + maxq - minq
@@ -484,7 +486,7 @@ def iterative_wls_quant_search(data, bits=4, rrmin=-1.0, rdelta=0.1, nstep=20, u
sum_l2 = torch.sum(mul_weights_quant_data * quant_data_new, dim=-1, keepdim=True)
sum_xl = torch.sum(mul_weights_quant_data * data, dim=-1, keepdim=True)
- D = sum_w * sum_l2 - sum_l**2
+ D = sum_w * sum_l2 - torch.pow(sum_l, 2)
this_scale = (sum_w * sum_xl - sum_x * sum_l) / D
this_min = (sum_l2 * sum_x - sum_l * sum_xl) / D
this_min[this_min > 0] = 0
@@ -494,7 +496,7 @@ def iterative_wls_quant_search(data, bits=4, rrmin=-1.0, rdelta=0.1, nstep=20, u
quant_data = torch.clamp(torch.round(reverse_this_scale * (data - this_min)), minq, maxq)
diff = this_scale * quant_data + this_min - data
# diff = this_scale * quant_data_new + this_min - data
- mad = torch.sum((weights * torch.abs(diff)) if use_mad else weights * diff**2, dim=-1, keepdim=True)
+ mad = torch.sum((weights * torch.abs(diff)) if use_mad else weights * torch.pow(diff, 2), dim=-1, keepdim=True)
idx_to_replace = torch.where((mad < best_mad) & (D > 0))[0]
best_mad[idx_to_replace] = mad[idx_to_replace]
@@ -566,7 +568,7 @@ def quant_tensor_gguf_sym_dq(
imatrix = imatrix.to(tensor.device)
# if bits == 3:
- # # sigma2 = 2 * torch.sum(tensor ** 2, dim=-1, keepdim=True) / QK_K
+ # # sigma2 = 2 * torch.sum(torch.pow(tensor, 2), dim=-1, keepdim=True) / QK_K
# # imatrix = imatrix.reshape(1, -1).expand(tensor.numel() // imatrix.numel(), -1).reshape(tensor.shape)
# # quant_weights = imatrix * torch.sqrt(sigma2 + tensor * tensor)
# # scale, int_w = make_qx_quants(tensor, bits=bits, rmse_type=1, qw=quant_weights)
@@ -588,7 +590,7 @@ def quant_tensor_gguf_sym_dq(
if bits == 6:
quant_weights[replace_index] = tensor[replace_index] * tensor[replace_index]
else:
- sigma2 = 2 * torch.sum(tensor**2, dim=-1, keepdim=True) / QK_K
+ sigma2 = 2 * torch.sum(torch.pow(tensor, 2), dim=-1, keepdim=True) / QK_K
tmp_quant_weights = torch.sqrt(sigma2 + tensor * tensor)
quant_weights[replace_index] = tmp_quant_weights[replace_index]
mean_replace_index = (zero_cnt > 0) & (zero_cnt <= group_size // 2)
diff --git a/auto_round/export/export_to_autogptq/export.py b/auto_round/export/export_to_autogptq/export.py
index 6c7558175..beeb3af14 100644
--- a/auto_round/export/export_to_autogptq/export.py
+++ b/auto_round/export/export_to_autogptq/export.py
@@ -47,6 +47,7 @@ import transformers
from tqdm import tqdm
import auto_round.export.export_to_autogptq.qlinear_triton
+from auto_round.export.utils import save_model
from auto_round.logger import logger
from auto_round.utils import (
SUPPORTED_LAYER_TYPES,
@@ -214,54 +215,7 @@ def save_quantized_as_autogptq(output_dir, inplace=True, backend="auto_gptq:exll
model.config.quantization_config = quantization_config
dtype = torch.float16 ##force dtype to fp16
- save(model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
+ save_model(
+ model, output_dir, safe_serialization=safe_serialization, dtype=dtype, config_file="quantize_config.json"
+ )
return model
-
-
-def save(
- model: torch.nn.Module, save_dir: str, max_shard_size: str = "5GB", safe_serialization: bool = True, dtype=None
-):
- """Save model state dict and configs.
-
- Args:
- model (`nn.Module`):
- Model to be saved. The model can be wrapped or unwrapped.
- save_dir (`str`):
- Directory to which to save. Will be created if it doesn't exist.
- max_shard_size (`str`, defaults to `"10GB"`):
- The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
- lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).
- <Tip warning={true}>
-
- If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard
- which will be bigger than `max_shard_size`.
-
- </Tip>
- safe_serialization (`bool`, defaults to `True`):
- Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
- """
- ##max_shard_size = "10000GB" ## API of auto-gptq with marlin does not support shard size
- os.makedirs(save_dir, exist_ok=True)
- try:
- model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
- except ValueError as e:
- if hasattr(model, "generation_config"):
- setattr(model.generation_config, "do_sample", True)
- model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
- config_path = os.path.join(save_dir, "config.json")
- if dtype is not None and dtype != model.dtype and os.path.exists(os.path.join(save_dir, "config.json")):
- with open(config_path, "r") as file:
- data = json.load(file)
- data["torch_dtype"] = str(dtype).split(".")[-1]
- with open(config_path, "w") as file:
- json.dump(data, file, indent=2)
-
- config_file = "quantize_config.json"
- 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)
-
- try:
- copy_python_files_from_model_cache(model, save_dir)
- except Exception as e:
- logger.warning("Skipping source model Python file copy due to error: %s", e)
diff --git a/auto_round/export/export_to_autoround/export.py b/auto_round/export/export_to_autoround/export.py
index 26d721ec0..7f134276b 100644
--- a/auto_round/export/export_to_autoround/export.py
+++ b/auto_round/export/export_to_autoround/export.py
@@ -27,6 +27,7 @@ import transformers
from tqdm import tqdm
from auto_round.export.export_to_autoround.utils import REQUIRED_CONFIG_KEYS, check_neq_config
+from auto_round.export.utils import save_model
from auto_round.logger import logger
from auto_round.utils import (
SUPPORTED_FORMATS,
@@ -47,7 +48,8 @@ from auto_round.utils import (
class AutoRoundFormat(str, Enum):
# Weight: FP8, per-channel, may be extended to per-tensor in future
# Activation: FP8, per-tensor
- TORCH_FP8_STATIC = "fp8_static"
+ FP8_STATIC = "fp8_static"
+ FP8 = "fp8"
def dynamic_import_quant_linear_for_packing(backend, bits, group_size, sym, act_bits=16):
@@ -159,11 +161,19 @@ def pack_layer(layer_name, model, backend, device=None):
return pack_layer(layer_name, model, backend, device)
- if backend == "auto_round:fp8" or backend == f"auto_round:{AutoRoundFormat.TORCH_FP8_STATIC.value}":
+ if (
+ backend == f"auto_round:{AutoRoundFormat.FP8.value}"
+ or backend == f"auto_round:{AutoRoundFormat.FP8_STATIC.value}"
+ ):
from auto_round.export.export_to_autoround.export_to_fp8 import pack_layer
return pack_layer(layer_name, model, backend, device)
+ if backend == "auto_round:llm_compressor":
+ from auto_round.export.export_to_llmcompressor.export_to_static_fp import pack_layer
+
+ return pack_layer(layer_name, model, backend, device)
+
layer = get_module(model, layer_name)
if hasattr(layer, "orig_layer"):
layer = layer.orig_layer
@@ -271,6 +281,11 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:ex
return save_quantized_as_fp(output_dir, inplace=inplace, backend="auto_round:llm_compressor", **kwargs)
+ if backend == "auto_round:llm_compressor":
+ from auto_round.export.export_to_llmcompressor.export_to_static_fp import save_quantized_as_static_fp
+
+ return save_quantized_as_static_fp(output_dir, inplace=inplace, backend="auto_round:llm_compressor", **kwargs)
+
if kwargs.get("data_type", "int") == "fp" and kwargs.get("bits", 16) == 8 and kwargs.get("act_bits", 16) >= 16:
from auto_round.export.export_to_autoround.export_to_fp8 import save_quantized_as_autoround
@@ -280,7 +295,7 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:ex
if (
(kwargs.get("sym") is None or kwargs.get("sym"))
and ("gptq" not in backend and "awq" not in backend)
- and (AutoRoundFormat.TORCH_FP8_STATIC.value not in backend)
+ and (AutoRoundFormat.FP8_STATIC.value not in backend)
):
backend = backend.replace("auto_round", "auto_round:auto_gptq")
@@ -367,52 +382,6 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round:ex
dtype = torch.float16 ## awq kernel only supports float16 on cuda
else:
dtype = None
- save(model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
+ save_model(model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
return model
-
-
-def save(model: nn.Module, save_dir: str, max_shard_size: str = "5GB", safe_serialization: bool = True, dtype=None):
- """Save model state dict and configs.
-
- Args:
- model (`nn.Module`):
- Model to be saved. The model can be wrapped or unwrapped.
- save_dir (`str`):
- Directory to which to save. Will be created if it doesn't exist.
- max_shard_size (`str`, defaults to `"10GB"`):
- The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
- lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).
- <Tip warning={true}>
-
- If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard
- which will be bigger than `max_shard_size`.
-
- </Tip>
- safe_serialization (`bool`, defaults to `True`):
- Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
- """
- os.makedirs(save_dir, exist_ok=True)
- try:
- model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
- except ValueError as e:
- if hasattr(model, "generation_config"):
- setattr(model.generation_config, "do_sample", True)
- model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
-
- config_path = os.path.join(save_dir, "config.json")
- if dtype is not None and dtype != model.dtype and os.path.exists(os.path.join(save_dir, "config.json")):
- with open(config_path, "r") as file:
- data = json.load(file)
- data["torch_dtype"] = str(dtype).split(".")[-1]
- with open(config_path, "w") as file:
- json.dump(data, file, indent=2)
- config_file = "quantization_config.json"
- 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)
-
- try:
- copy_python_files_from_model_cache(model, save_dir)
- except Exception as e:
- logger.warning("Skipping source model Python file copy due to error: %s", e)
diff --git a/auto_round/export/export_to_autoround/export_to_fp8.py b/auto_round/export/export_to_autoround/export_to_fp8.py
index 4d0cb5033..1e0eb1b29 100644
--- a/auto_round/export/export_to_autoround/export_to_fp8.py
+++ b/auto_round/export/export_to_autoround/export_to_fp8.py
@@ -24,6 +24,7 @@ from tqdm import tqdm
from auto_round.data_type.utils import reshape_pad_tensor_by_group_size, revert_tensor_by_pad
from auto_round.export.export_to_autoround.utils import REQUIRED_CONFIG_KEYS, check_neq_config
+from auto_round.export.utils import save_model
from auto_round.logger import logger
from auto_round.utils import (
SUPPORTED_LAYER_TYPES,
@@ -37,7 +38,7 @@ from auto_round.utils import (
)
-class FP8WOQLinear(torch.nn.Module):
+class FP8QLinear(torch.nn.Module):
def __init__(
self,
@@ -128,7 +129,7 @@ def pack_layer(layer_name, model, data_type, device=None):
in_features = layer.weight.shape[0]
out_features = layer.weight.shape[1]
bias = layer.bias
- my_linear = FP8WOQLinear(
+ my_linear = FP8QLinear(
in_features,
out_features,
weight=q_weight,
@@ -231,48 +232,6 @@ def save_quantized_as_autoround(output_dir, inplace=True, backend="auto_round",
dtype = torch.float16 ## awq kernel only supports float16 on cuda
else:
dtype = None
- save(model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
+ save_model(model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
return model
-
-
-def save(
- model: torch.nn.Module, save_dir: str, max_shard_size: str = "5GB", safe_serialization: bool = True, dtype=None
-):
- """Save model state dict and configs.
-
- Args:
- model (`nn.Module`):
- Model to be saved. The model can be wrapped or unwrapped.
- save_dir (`str`):
- Directory to which to save. Will be created if it doesn't exist.
- max_shard_size (`str`, defaults to `"10GB"`):
- The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
- lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).
- <Tip warning={true}>
-
- If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard
- which will be bigger than `max_shard_size`.
-
- </Tip>
- safe_serialization (`bool`, defaults to `True`):
- Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
- """
- os.makedirs(save_dir, exist_ok=True)
- model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
- config_path = os.path.join(save_dir, "config.json")
- if dtype is not None and dtype != model.dtype and os.path.exists(os.path.join(save_dir, "config.json")):
- with open(config_path, "r") as file:
- data = json.load(file)
- data["torch_dtype"] = str(dtype).split(".")[-1]
- with open(config_path, "w") as file:
- json.dump(data, file, indent=2)
- config_file = "quantization_config.json"
- 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)
-
- try:
- copy_python_files_from_model_cache(model, save_dir)
- except Exception as e:
- logger.warning("Skipping source model Python file copy due to error: %s", e)
diff --git a/auto_round/export/export_to_autoround/export_to_nvfp_mxfp.py b/auto_round/export/export_to_autoround/export_to_nvfp_mxfp.py
index bd04146e9..e56531696 100644
--- a/auto_round/export/export_to_autoround/export_to_nvfp_mxfp.py
+++ b/auto_round/export/export_to_autoround/export_to_nvfp_mxfp.py
@@ -25,6 +25,7 @@ import transformers
from tqdm import tqdm
from auto_round.export.export_to_autoround.utils import REQUIRED_CONFIG_KEYS, check_neq_config
+from auto_round.export.utils import save_model
from auto_round.logger import logger
from auto_round.utils import (
SUPPORTED_LAYER_TYPES,
@@ -250,46 +251,6 @@ def save_quantized_as_fp(output_dir, inplace=True, **kwargs):
processor.save_pretrained(output_dir)
dtype = None
- save(model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
+ save_model(model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
return model
-
-
-def save(model: nn.Module, save_dir: str, max_shard_size: str = "5GB", safe_serialization: bool = True, dtype=None):
- """Save model state dict and configs.
-
- Args:
- model (`nn.Module`):
- Model to be saved. The model can be wrapped or unwrapped.
- save_dir (`str`):
- Directory to which to save. Will be created if it doesn't exist.
- max_shard_size (`str`, defaults to `"10GB"`):
- The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
- lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).
- <Tip warning={true}>
-
- If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard
- which will be bigger than `max_shard_size`.
-
- </Tip>
- safe_serialization (`bool`, defaults to `True`):
- Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
- """
- os.makedirs(save_dir, exist_ok=True)
- model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
- config_path = os.path.join(save_dir, "config.json")
- if dtype is not None and dtype != model.dtype and os.path.exists(os.path.join(save_dir, "config.json")):
- with open(config_path, "r") as file:
- data = json.load(file)
- data["torch_dtype"] = str(dtype).split(".")[-1]
- with open(config_path, "w") as file:
- json.dump(data, file, indent=2)
- config_file = "quantization_config.json"
- 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)
-
- try:
- copy_python_files_from_model_cache(model, save_dir)
- except Exception as e:
- logger.warning("Skipping source model Python file copy due to error: %s", e)
diff --git a/auto_round/export/export_to_awq/export.py b/auto_round/export/export_to_awq/export.py
index 21e1e470f..6da6bec3e 100644
--- a/auto_round/export/export_to_awq/export.py
+++ b/auto_round/export/export_to_awq/export.py
@@ -31,6 +31,7 @@ import torch.nn as nn
from tqdm import tqdm
from auto_round.export.export_to_awq.utils import WQLinear_GEMM
+from auto_round.export.utils import save_model
from auto_round.logger import logger
from auto_round.utils import (
SUPPORTED_LAYER_TYPES,
@@ -155,51 +156,6 @@ def save_quantized_as_autoawq(output_dir, inplace=True, **kwargs):
compressed_model.config.quantization_config = quantization_config
safe_serialization = kwargs.get("safe_serialization", True)
dtype = torch.float16 ##force dtype to fp16
- save(compressed_model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
+ save_model(compressed_model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
return compressed_model
-
-
-def save(model: nn.Module, save_dir: str, max_shard_size: str = "5GB", safe_serialization: bool = True, dtype=None):
- """Save model state dict and configs.
-
- Args:
- model (`nn.Module`):
- Model to be saved. The model can be wrapped or unwrapped.
- save_dir (`str`):
- Directory to which to save. Will be created if it doesn't exist.
- max_shard_size (`str`, defaults to `"10GB"`):
- The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
- lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).
- <Tip warning={true}>
-
- If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard
- which will be bigger than `max_shard_size`.
-
- </Tip>
- safe_serialization (`bool`, defaults to `True`):
- Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
- """
- os.makedirs(save_dir, exist_ok=True)
- try:
- model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
- except ValueError as e:
- if hasattr(model, "generation_config"):
- setattr(model.generation_config, "do_sample", True)
- model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
- config_path = os.path.join(save_dir, "config.json")
- if dtype is not None and dtype != model.dtype and os.path.exists(os.path.join(save_dir, "config.json")):
- with open(config_path, "r") as file:
- data = json.load(file)
- data["torch_dtype"] = str(dtype).split(".")[-1]
- with open(config_path, "w") as file:
- json.dump(data, file, indent=2)
- config_file = "quantization_config.json"
- 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)
-
- try:
- copy_python_files_from_model_cache(model, save_dir)
- except Exception as e:
- logger.warning("Skipping source model Python file copy due to error: %s", e)
diff --git a/auto_round/export/export_to_gguf/packing.py b/auto_round/export/export_to_gguf/packing.py
index f831c6939..b2fbfaf1c 100644
--- a/auto_round/export/export_to_gguf/packing.py
+++ b/auto_round/export/export_to_gguf/packing.py
@@ -106,7 +106,7 @@ def make_qx_quants(data, bits, rmse_type=0, qw=None):
if qw is not None:
w = qw
elif rmse_type == 1:
- w = data**2
+ w = torch.pow(data, 2)
elif rmse_type == 2:
w = 1
elif rmse_type == 3:
@@ -155,7 +155,7 @@ def make_q3_quants(data, bits, do_rmse=False):
w_tmp, data_tmp, L_tmp = w[:, :, i], data[:, :, i], L[:, :, i]
slx = sumlx - w_tmp * data_tmp * L_tmp
replace_idx = slx > 0
- sl2 = suml2 - w_tmp * L_tmp**2
+ sl2 = suml2 - w_tmp * torch.pow(L_tmp, 2)
new_L = torch.round(data_tmp * sl2 / slx).clip(-nmax, nmax - 1)
tmp_replace_idx = replace_idx & (new_L != L_tmp)
slx[tmp_replace_idx] += w_tmp[tmp_replace_idx] * data_tmp[tmp_replace_idx] * new_L[tmp_replace_idx]
@@ -207,7 +207,7 @@ def make_qkx2_quants(data, bits, weights=None, rmin=-1.0, rdelta=0.1, nstep=20,
L = torch.clip(l_values, 0, nmax).to(torch.uint8)
diffs = scale * L + group_min - data
- diffs = torch.abs(diffs) if use_mad else diffs**2
+ diffs = torch.abs(diffs) if use_mad else torch.pow(diffs, 2)
best_mad = torch.sum(weights * diffs, dim=-1, keepdim=True)
if nstep < 1:
@@ -221,7 +221,7 @@ def make_qkx2_quants(data, bits, weights=None, rmin=-1.0, rdelta=0.1, nstep=20,
Laux = torch.clip(l_values, 0, nmax).to(torch.uint8)
sum_l = torch.sum(weights * Laux, dim=-1, keepdim=True)
- sum_l2 = torch.sum(weights * Laux**2, dim=-1, keepdim=True)
+ sum_l2 = torch.sum(weights * torch.pow(Laux, 2), dim=-1, keepdim=True)
sum_xl = torch.sum(weights * Laux * data, dim=-1, keepdim=True)
D = sum_w * sum_l2 - sum_l * sum_l
@@ -233,7 +233,7 @@ def make_qkx2_quants(data, bits, weights=None, rmin=-1.0, rdelta=0.1, nstep=20,
this_scale[this_min > 0] = (sum_xl / sum_l2)[this_min > 0]
diffs = this_scale * Laux + this_min - data
- diffs = torch.abs(diffs) if use_mad else diffs**2
+ diffs = torch.abs(diffs) if use_mad else torch.pow(diffs, 2)
mad = torch.sum(weights * diffs, dim=-1, keepdim=True)
replace_idx &= mad < best_mad
diff --git a/auto_round/export/export_to_llmcompressor/export.py b/auto_round/export/export_to_llmcompressor/export.py
index f55ac280c..938411b3a 100644
--- a/auto_round/export/export_to_llmcompressor/export.py
+++ b/auto_round/export/export_to_llmcompressor/export.py
@@ -18,6 +18,8 @@ import os
import torch
from auto_round.export.export_to_llmcompressor.config import quantization_config
+from auto_round.export.export_to_llmcompressor.export_to_fp import save_quantized_as_fp
+from auto_round.export.export_to_llmcompressor.export_to_static_fp import save_quantized_as_static_fp
from auto_round.logger import logger
from auto_round.utils import (
copy_python_files_from_model_cache,
@@ -26,12 +28,11 @@ from auto_round.utils import (
is_mx_fp,
is_nv_fp,
is_standard_fp,
+ is_static_wfp8afp8,
set_module,
)
from auto_round.wrapper import WrapperWALayer
-from .export_to_fp import save_quantized_as_fp
-
@torch.no_grad()
def recover_qweight(qdq_weight, scale):
@@ -70,6 +71,11 @@ def pack_layer(layer_name, model, backend, device=None):
return pack_layer(layer_name, model, backend, device)
+ if is_static_wfp8afp8(backend):
+ from auto_round.export.export_to_llmcompressor.export_to_static_fp import pack_layer
+
+ return pack_layer(layer_name, model, backend, device)
+
## passed as no other llm_compressor format is supported yet
logger.warning("No other llm_compressor packing format(except NVFP&MXFP) is supported yet, skip packing")
return
@@ -105,6 +111,9 @@ def save_quantized_as_llmcompressor(output_dir: str, inplace: bool = True, **kwa
if is_nv_fp(backend) or is_mx_fp(backend):
return save_quantized_as_fp(output_dir, inplace=inplace, **kwargs)
+ if is_static_wfp8afp8(backend):
+ return save_quantized_as_static_fp(output_dir, **kwargs)
+
model = kwargs.get("model", None)
safe_serialization = kwargs.get("safe_serialization", True)
tokenizer = kwargs.get("tokenizer", None)
diff --git a/auto_round/export/export_to_llmcompressor/export_to_fp.py b/auto_round/export/export_to_llmcompressor/export_to_fp.py
index 6581f0c6f..37899238a 100644
--- a/auto_round/export/export_to_llmcompressor/export_to_fp.py
+++ b/auto_round/export/export_to_llmcompressor/export_to_fp.py
@@ -25,6 +25,7 @@ import transformers
from tqdm import tqdm
from auto_round.export.export_to_autoround.qlinear_fp import QuantLinear
+from auto_round.export.utils import save_model
from auto_round.logger import logger
from auto_round.utils import (
SUPPORTED_LAYER_TYPES,
@@ -242,46 +243,6 @@ def save_quantized_as_fp(output_dir, inplace=True, **kwargs):
processor.save_pretrained(output_dir)
dtype = None
- save(model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
+ save_model(model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
return model
-
-
-def save(model: nn.Module, save_dir: str, max_shard_size: str = "5GB", safe_serialization: bool = True, dtype=None):
- """Save model state dict and configs.
-
- Args:
- model (`nn.Module`):
- Model to be saved. The model can be wrapped or unwrapped.
- save_dir (`str`):
- Directory to which to save. Will be created if it doesn't exist.
- max_shard_size (`str`, defaults to `"10GB"`):
- The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
- lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).
- <Tip warning={true}>
-
- If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard
- which will be bigger than `max_shard_size`.
-
- </Tip>
- safe_serialization (`bool`, defaults to `True`):
- Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
- """
- os.makedirs(save_dir, exist_ok=True)
- model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
- config_path = os.path.join(save_dir, "config.json")
- if dtype is not None and dtype != model.dtype and os.path.exists(os.path.join(save_dir, "config.json")):
- with open(config_path, "r") as file:
- data = json.load(file)
- data["torch_dtype"] = str(dtype).split(".")[-1]
- with open(config_path, "w") as file:
- json.dump(data, file, indent=2)
- config_file = "quantization_config.json"
- 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)
-
- try:
- copy_python_files_from_model_cache(model, save_dir)
- except Exception as e:
- logger.warning("Skipping source model Python file copy due to error: %s", e)
diff --git a/auto_round/export/export_to_llmcompressor/export_to_static_fp.py b/auto_round/export/export_to_llmcompressor/export_to_static_fp.py
new file mode 100644
index 000000000..0d0681074
--- /dev/null
+++ b/auto_round/export/export_to_llmcompressor/export_to_static_fp.py
@@ -0,0 +1,245 @@
+# 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 copy
+import json
+import os
+import sys
+from concurrent.futures import ThreadPoolExecutor
+
+import threadpoolctl as tctl
+import torch
+import transformers
+from tqdm import tqdm
+
+from auto_round.data_type.utils import reshape_pad_tensor_by_group_size, revert_tensor_by_pad
+from auto_round.export.export_to_autoround.export_to_fp8 import FP8QLinear
+from auto_round.export.export_to_llmcompressor.config import check_compressed_tensors_supported
+from auto_round.export.utils import save_model
+from auto_round.utils import (
+ SUPPORTED_LAYER_TYPES,
+ _get_packing_device,
+ check_start_with_block_name,
+ check_to_quantized,
+ copy_python_files_from_model_cache,
+ filter_quantization_config,
+ get_module,
+ logger,
+ set_module,
+)
+
+
+def pack_layer(layer_name: str, model: torch.nn.Module, data_type: str, device: str = None) -> None:
+ """
+ Packs a model layer for quantization based on its type and configuration.
+
+ This function retrieves the specified layer from the model, checks its
+ compatibility for quantization, and replaces it with a quantized version
+ if applicable. The quantization process depends on the layer's bit-width,
+ group size, symmetry, and activation bits.
+
+ Args:
+ layer_name (str): The name of the layer to be packed.
+ model (torch.nn.Module): The model containing the layer.
+ backend (str): The backend framework to be used for quantization.
+
+ Returns:
+ None: The function modifies the model in place.
+ """
+ packing_device = _get_packing_device(device)
+ layer = get_module(model, layer_name)
+ if hasattr(layer, "orig_layer"):
+ layer = layer.orig_layer
+
+ if not isinstance(layer, SUPPORTED_LAYER_TYPES): ##already packed
+ return
+
+ if not check_to_quantized(layer):
+ return
+
+ orig_device = layer.weight.device
+ scale = layer.scale.view(-1)
+ zp = layer.zp
+ weight = layer.weight
+ weight, orig_shape, pad_len = reshape_pad_tensor_by_group_size(weight, layer.group_size)
+ act_scale = layer.act_scale.view(-1) if hasattr(layer, "act_scale") else None
+ torch_dtype = torch.float8_e4m3fn
+ if "fp8_e5m2" in data_type:
+ torch_dtype = torch.float8_e5m2
+ info = torch.finfo(torch_dtype)
+ if zp is not None:
+ q_weight = (
+ weight.to(packing_device) / scale.to(packing_device).unsqueeze(-1) + zp.to(packing_device)
+ if isinstance(zp, torch.Tensor)
+ else zp
+ )
+ else:
+ q_weight = weight.to(packing_device) / scale.to(packing_device).unsqueeze(-1)
+ q_weight = revert_tensor_by_pad(q_weight, orig_shape=orig_shape, pad_len=pad_len)
+ q_weight = torch.clamp(q_weight, info.min, info.max)
+ q_weight = q_weight.to(torch_dtype)
+ if isinstance(layer, torch.nn.Linear):
+ in_features = layer.in_features
+ out_features = layer.out_features
+ elif isinstance(layer, transformers.pytorch_utils.Conv1D):
+ in_features = layer.weight.shape[0]
+ out_features = layer.weight.shape[1]
+ bias = layer.bias
+ my_linear = FP8QLinear(
+ in_features,
+ out_features,
+ weight=q_weight,
+ weight_scale=scale,
+ bias=bias,
+ weight_zp=zp,
+ input_scale=act_scale,
+ dtype=model.dtype,
+ )
+ if len(my_linear.weight_scale.shape) and my_linear.weight_scale.shape[0] != 1:
+ my_linear.weight_scale = my_linear.weight_scale.reshape(-1, 1)
+
+ my_linear.to(orig_device)
+ set_module(model, layer_name, my_linear)
+
+
+def save_quantized_as_static_fp(output_dir: str, inplace: bool = True, **kwargs) -> torch.nn.Module:
+ """
+ Saves a quantized model of FP8_STATIC scheme in the llm-compressor format.
+
+ Args:
+ output_dir (str): The directory where the quantized model will be saved.
+ inplace (bool, optional): If True, modifies the model in place. Otherwise, creates a deepcopy of the model.
+ Default is True.
+ backend (str, optional): The backend to be used for quantization.
+ Default is "autoround:exllamav2".
+ **kwargs: Additional keyword arguments including:
+ - model (nn.Module): The model to be quantized.
+ - layer_config (dict): The layer configuration for each layer.
+ - serialization_dict (dict): The serialization configuration.
+ - tokenizer (Tokenizer, optional): The tokenizer to be saved.
+
+ Returns:
+ None
+
+ Raises:
+ ValueError: If the backend is not supported.
+ """
+ model = kwargs["model"]
+ safe_serialization = True if "safe_serialization" not in kwargs.keys() else kwargs["safe_serialization"]
+ if not inplace:
+ model = copy.deepcopy(model.to("cpu"))
+
+ layer_config = kwargs["layer_config"]
+ tokenizer = kwargs.get("tokenizer", None)
+ processor = kwargs.get("processor", None)
+ device = kwargs.get("device", None)
+ image_processor = kwargs.get("image_processor", None)
+
+ names = list(layer_config.keys())
+ max_workers = 1
+ if not torch.cuda.is_available() and not torch.xpu.is_available():
+ max_workers = 2 ## 2 with cuda packing will cause hang occasionally
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ with tqdm(total=len(names), leave=True) as pbar:
+
+ def wrapper(name):
+ pbar.set_description(f"packing {name}")
+ with tctl.threadpool_limits(limits=1):
+ pack_layer(name, model, kwargs.get("data_type", "fp8"), device)
+ pbar.update(1)
+
+ for _ in executor.map(wrapper, names):
+ pass
+
+ # Get llm-compressor format config
+ check_compressed_tensors_supported()
+ from compressed_tensors.quantization import ( # pylint: disable=E0401
+ QuantizationArgs,
+ QuantizationConfig,
+ QuantizationScheme,
+ QuantizationStatus,
+ QuantizationStrategy,
+ QuantizationType,
+ )
+
+ group_size = kwargs["serialization_dict"]["group_size"]
+ if group_size == -1:
+ strategy = QuantizationStrategy.CHANNEL
+ elif group_size == 0:
+ strategy = QuantizationStrategy.TENSOR
+ else:
+ strategy = QuantizationStrategy.GROUP
+ if kwargs["serialization_dict"]["act_group_size"] != 0:
+ logger.error(
+ f"scheme FP8_STATIC export to llm_compressor format only support for act_group_size 0,"
+ f" but got {kwargs['serialization_dict']['act_group_size']}, please check."
+ )
+ sys.exit(-1)
+ scheme_args = dict(
+ weights=QuantizationArgs(
+ num_bits=8,
+ type=QuantizationType.FLOAT,
+ strategy=strategy,
+ symmetric=True,
+ dynamic=False,
+ ),
+ input_activations=QuantizationArgs(
+ num_bits=8,
+ type=QuantizationType.FLOAT,
+ strategy=QuantizationStrategy.TENSOR,
+ symmetric=True,
+ dynamic=False,
+ ),
+ )
+ targets = ["Linear"]
+ ignore = []
+ for layer_name in layer_config:
+ if not check_to_quantized(layer_config[layer_name]):
+ ignore.append(layer_name)
+ config_groups = {}
+ scheme = QuantizationScheme(targets=targets, **scheme_args)
+ config_groups["group_0"] = scheme
+ quantization_config = QuantizationConfig(
+ config_groups=config_groups,
+ kv_cache_scheme=None,
+ quantization_status=QuantizationStatus.COMPRESSED,
+ ignore=ignore,
+ )
+ quantization_config = quantization_config.to_dict()
+ quantization_config["provider"] = "auto-round"
+ quantization_config["format"] = "float-quantized"
+ if group_size > 0:
+ quantization_config["config_groups"]["group_0"]["weights"]["group_size"] = group_size
+ if hasattr(model, "config"):
+ model.config.quantization_config = quantization_config
+
+ if output_dir is None:
+ return model
+
+ if os.path.exists(output_dir):
+ logger.warning(f"{output_dir} already exists, this may cause model conflict")
+
+ if tokenizer is not None:
+ tokenizer.save_pretrained(output_dir)
+
+ if processor is not None:
+ processor.save_pretrained(output_dir)
+
+ if image_processor is not None:
+ image_processor.save_pretrained(output_dir)
+
+ dtype = None
+ save_model(model, output_dir, safe_serialization=safe_serialization, dtype=dtype)
+
+ return model
diff --git a/auto_round/export/utils.py b/auto_round/export/utils.py
new file mode 100644
index 000000000..716d0afd3
--- /dev/null
+++ b/auto_round/export/utils.py
@@ -0,0 +1,72 @@
+# 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 json
+import os
+
+import torch.nn as nn
+
+from auto_round.utils import copy_python_files_from_model_cache, logger
+
+
+def save_model(
+ model: nn.Module,
+ save_dir: str,
+ max_shard_size: str = "5GB",
+ safe_serialization: bool = True,
+ dtype=None,
+ config_file="quantization_config.json",
+):
+ """Save model state dict and configs.
+
+ Args:
+ model (`nn.Module`):
+ Model to be saved. The model can be wrapped or unwrapped.
+ save_dir (`str`):
+ Directory to which to save. Will be created if it doesn't exist.
+ max_shard_size (`str`, defaults to `"10GB"`):
+ The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
+ lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).
+ <Tip warning={true}>
+
+ If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard
+ which will be bigger than `max_shard_size`.
+
+ </Tip>
+ safe_serialization (`bool`, defaults to `True`):
+ Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
+ """
+ os.makedirs(save_dir, exist_ok=True)
+ try:
+ model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
+ except ValueError as e:
+ if hasattr(model, "generation_config"):
+ setattr(model.generation_config, "do_sample", True)
+ model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
+
+ config_path = os.path.join(save_dir, "config.json")
+ if dtype is not None and dtype != model.dtype and os.path.exists(os.path.join(save_dir, "config.json")):
+ with open(config_path, "r") as file:
+ data = json.load(file)
+ data["torch_dtype"] = str(dtype).split(".")[-1]
+ with open(config_path, "w") as file:
+ json.dump(data, file, indent=2)
+ config_file = "quantization_config.json"
+ 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)
+
+ try:
+ copy_python_files_from_model_cache(model, save_dir)
+ except Exception as e:
+ logger.warning("Skipping source model Python file copy due to error: %s", e)
diff --git a/auto_round/inference/backend.py b/auto_round/inference/backend.py
index 8a946b966..139a98120 100644
--- a/auto_round/inference/backend.py
+++ b/auto_round/inference/backend.py
@@ -471,7 +471,7 @@ def dynamic_import_inference_linear(backend, config):
"""
bits, group_size, sym = config["bits"], config["group_size"], config["sym"]
- if AutoRoundFormat.TORCH_FP8_STATIC.value in backend:
+ if AutoRoundFormat.FP8_STATIC.value in backend:
from auto_round.experimental.qmodules.fp8_static import WeightFP8ActFP8StaticQuantLinear
return WeightFP8ActFP8StaticQuantLinear
diff --git a/auto_round/inference/convert_model.py b/auto_round/inference/convert_model.py
index fcfb83b4c..827b1744c 100644
--- a/auto_round/inference/convert_model.py
+++ b/auto_round/inference/convert_model.py
@@ -452,7 +452,7 @@ def _create_quant_layer(layer, layer_backend, config, in_features, out_features)
out_features=out_features,
bias=bias,
)
- elif AutoRoundFormat.TORCH_FP8_STATIC.value in layer_backend:
+ elif AutoRoundFormat.FP8_STATIC.value in layer_backend:
return QuantLinear.from_original(config, layer)
# Default quantized layer creation
try:
diff --git a/auto_round/utils.py b/auto_round/utils.py
index 2d98ae121..b472e4d88 100644
--- a/auto_round/utils.py
+++ b/auto_round/utils.py
@@ -53,6 +53,7 @@ class SupportedFormats:
"auto_round:auto_gptq",
"auto_round:gptqmodel",
"auto_round:auto_awq",
+ "auto_round:llm_compressor",
"itrex",
"itrex_xpu",
"fake",
@@ -1451,6 +1452,8 @@ def llm_load_model(
)
torch.cuda.get_device_capability = orig_func
logger.warning("the support for fp8 model as input is experimental, please use with caution.")
+ else:
+ raise
except OSError as e:
logger.warning(
@@ -2537,10 +2540,12 @@ def is_wfp8afp8(ar):
return False
-def is_static_wfp8afp8(ar):
- if ar.act_dynamic:
+def is_static_wfp8afp8(ar_or_format: Union[str, Callable]) -> bool:
+ if isinstance(ar_or_format, str):
+ return "fp8_static" in ar_or_format
+ if ar_or_format.act_dynamic:
return False
- if is_wfp8afp8(ar):
+ if is_wfp8afp8(ar_or_format):
return True
return False
diff --git a/test/test_cpu/test_act_quantization.py b/test/test_cpu/test_act_quantization.py
index fd9ed2406..c12a9014a 100644
--- a/test/test_cpu/test_act_quantization.py
+++ b/test/test_cpu/test_act_quantization.py
@@ -22,7 +22,7 @@ class LLMDataLoader:
class TestAutoRoundAct(unittest.TestCase):
@classmethod
def setUpClass(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
self.model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
self.llm_dataloader = LLMDataLoader()
@@ -33,7 +33,7 @@ class TestAutoRoundAct(unittest.TestCase):
shutil.rmtree("runs", ignore_errors=True)
def test_mx_fp4(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
bits, group_size, sym = 4, 128, True
@@ -52,7 +52,7 @@ class TestAutoRoundAct(unittest.TestCase):
autoround.quantize()
def test_wint4fp8_dynamic(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
bits, group_size = 4, 128
@@ -89,7 +89,7 @@ class TestAutoRoundAct(unittest.TestCase):
autoround.quantize()
def test_wfp8afp8_static(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
from auto_round.wrapper import WrapperWALayer
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
@@ -112,7 +112,7 @@ class TestAutoRoundAct(unittest.TestCase):
self.assertEqual(autoround.model.model.decoder.layers[2].self_attn.k_proj.orig_layer.act_scale.shape[0], 30)
self.assertEqual(autoround.model.model.decoder.layers[2].self_attn.k_proj.orig_layer.act_max.shape[0], 30)
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
autoround = AutoRound(
diff --git a/test/test_cpu/test_autoopt.py b/test/test_cpu/test_autoopt.py
index 4f07c4e22..f9801217e 100644
--- a/test/test_cpu/test_autoopt.py
+++ b/test/test_cpu/test_autoopt.py
@@ -23,7 +23,7 @@ class LLMDataLoader:
class TestAutoRound(unittest.TestCase):
@classmethod
def setUpClass(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
self.model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
self.llm_dataloader = LLMDataLoader()
diff --git a/test/test_cpu/test_autoround.py b/test/test_cpu/test_autoround.py
index 827688812..9857cdc0d 100644
--- a/test/test_cpu/test_autoround.py
+++ b/test/test_cpu/test_autoround.py
@@ -28,7 +28,7 @@ class LLMDataLoader:
class TestAutoRound(unittest.TestCase):
@classmethod
def setUpClass(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
self.model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
self.llm_dataloader = LLMDataLoader()
@@ -41,14 +41,16 @@ class TestAutoRound(unittest.TestCase):
def test_bits_setting(self):
layer_config = {"model.decoder.layers.0.self_attn.k_proj": {"data_type": "mx_fp8", "group_size": 32}}
- autoround = AutoRound("facebook/opt-125m", iters=2, seqlen=2, nsamples=1, layer_config=layer_config)
+ autoround = AutoRound(
+ "/tf_dataset/auto_round/models/facebook/opt-125m", iters=2, seqlen=2, nsamples=1, layer_config=layer_config
+ )
autoround.quantize()
module = get_module(autoround.model, "model.decoder.layers.0.self_attn.k_proj")
if module.bits != 8:
raise ValueError(f"Expected bits to be 8, but got {module.bits}")
def test_remove_whole_block(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
layer_config = {
"model.decoder.layers.0.self_attn.k_proj": {"bits": 32},
"model.decoder.layers.0.self_attn.v_proj": {"bits": 32},
@@ -84,8 +86,12 @@ class TestAutoRound(unittest.TestCase):
)
autoround.quantize()
- model = AutoModelForCausalLM.from_pretrained("microsoft/phi-2", torch_dtype="auto", trust_remote_code=True)
- tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-2", trust_remote_code=True)
+ model = AutoModelForCausalLM.from_pretrained(
+ "/tf_dataset/auto_round/models/microsoft/phi-2", torch_dtype="auto", trust_remote_code=True
+ )
+ tokenizer = AutoTokenizer.from_pretrained(
+ "/tf_dataset/auto_round/models/microsoft/phi-2", trust_remote_code=True
+ )
autoround = AutoRound(
model,
tokenizer,
@@ -99,7 +105,7 @@ class TestAutoRound(unittest.TestCase):
autoround.quantize()
def test_mx_fp4(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
bits, group_size, sym = 4, 32, False
autoround = AutoRound(
model_name,
@@ -121,7 +127,7 @@ class TestAutoRound(unittest.TestCase):
self.assertGreater(result["results"]["lambada_openai"]["acc,none"], 0.3) # 0.375
def test_nv_fp4(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
bits, group_size, sym = 4, 16, False
autoround = AutoRound(
model_name,
@@ -163,7 +169,7 @@ class TestAutoRound(unittest.TestCase):
autoround.save_quantized(output_dir="./saved", inplace=False)
def test_w4g1(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
bits, group_size, sym = 4, -1, True
autoround = AutoRound(
model_name,
@@ -178,7 +184,7 @@ class TestAutoRound(unittest.TestCase):
@parameterized.expand([(2,), (3,), (4,)])
def test_g128(self, bits):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
group_size, sym = 128, True
autoround = AutoRound(
model_name,
@@ -214,7 +220,7 @@ class TestAutoRound(unittest.TestCase):
def test_enable_norm_bias_tuning_qwen3(self):
bits, group_size, sym = 4, 128, True
- model_name = "Qwen/Qwen3-0.6B"
+ model_name = "/tf_dataset/auto_round/models/Qwen/Qwen3-0.6B"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
autoround = AutoRound(
@@ -263,7 +269,7 @@ class TestAutoRound(unittest.TestCase):
#
def test_signround(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
bits, group_size, sym = 4, -1, False
autoround = AutoRound(
model_name,
@@ -297,7 +303,7 @@ class TestAutoRound(unittest.TestCase):
autoround.quantize()
def test_wa_quant(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
bits, group_size, sym, act_bits = 4, 128, False, 4
autoround = AutoRound(
model_name,
@@ -313,7 +319,7 @@ class TestAutoRound(unittest.TestCase):
def test_auto_device_map(self):
bits, group_size, sym = 4, 128, False
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(
model_name, torch_dtype="auto", trust_remote_code=True, device_map="auto"
)
@@ -331,7 +337,7 @@ class TestAutoRound(unittest.TestCase):
def test_fp32(self):
bits, group_size, sym = 4, 128, False
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(
model_name, torch_dtype=torch.float32, trust_remote_code=True, device_map="auto"
)
@@ -363,7 +369,7 @@ class TestAutoRound(unittest.TestCase):
autoround.quantize()
def test_rtn(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
@@ -383,7 +389,7 @@ class TestAutoRound(unittest.TestCase):
def test_embed_quant(self):
bits, group_size, sym = 4, 128, True
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
layer_config = {
"model.decoder.embed_tokens": {"bits": 4},
}
@@ -402,7 +408,7 @@ class TestAutoRound(unittest.TestCase):
def test_fallback_layers(self):
bits, group_size, sym = 4, 128, True
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(
model_name, torch_dtype=torch.float32, trust_remote_code=True, device_map="auto"
)
@@ -444,7 +450,7 @@ class TestAutoRound(unittest.TestCase):
from auto_round_extension.ipex.qlinear_ipex_awq import QuantLinear
- model_name = "Qwen/Qwen2-VL-2B-Instruct-AWQ"
+ model_name = "/tf_dataset/auto_round/models/Qwen/Qwen2-VL-2B-Instruct-AWQ"
quantization_config = AutoRoundConfig()
model = Qwen2VLForConditionalGeneration.from_pretrained(
model_name, quantization_config=quantization_config, device_map="cpu", torch_dtype=torch.float16
@@ -490,7 +496,7 @@ class TestAutoRound(unittest.TestCase):
print(output_text)
def test_fallback_layers_regex_awq(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
bits, group_size, sym = 4, 128, True
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
@@ -526,7 +532,7 @@ class TestAutoRound(unittest.TestCase):
shutil.rmtree(self.save_folder, ignore_errors=True)
def test_fallback_layers_regex_gptq(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
bits, group_size, sym = 4, 128, True
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
@@ -562,7 +568,7 @@ class TestAutoRound(unittest.TestCase):
shutil.rmtree(self.save_folder, ignore_errors=True)
def test_fallback_layers_regex_round(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
bits, group_size, sym = 4, 128, True
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
@@ -598,7 +604,7 @@ class TestAutoRound(unittest.TestCase):
shutil.rmtree(self.save_folder, ignore_errors=True)
def test_fallback_layers_regex_exception(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
bits, group_size, sym = 4, 128, True
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
@@ -647,7 +653,7 @@ class TestAutoRound(unittest.TestCase):
self.assertEqual(dequant_weight.shape.numel(), 32 * 5760 * 1440)
def test_mixed_bit_setting(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
layer_config = {"model.decoder.layers.7.fc1": {"bits": 8, "act_bits": 8}}
ar = AutoRound(model_name, data_type="mx_fp4", act_bits=4, iters=0, layer_config=layer_config)
ar.quantize()
@@ -659,21 +665,33 @@ class TestAutoRound(unittest.TestCase):
raise ValueError("mixed bits is not correct")
def test_alg_ext(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
ar = AutoRound(model_name, scheme="W2A16", iters=1, nsamples=1, enable_alg_ext=True)
ar.quantize()
def test_invalid_layer_config(self):
with self.assertRaises(ValueError):
layer_config = {"model.decoder.layers.2.self_attnx": {"bits": 2}}
- ar = AutoRound("facebook/opt-125m", scheme="W3A16", nsamples=1, iters=1, layer_config=layer_config)
+ ar = AutoRound(
+ "/tf_dataset/auto_round/models/facebook/opt-125m",
+ scheme="W3A16",
+ nsamples=1,
+ iters=1,
+ layer_config=layer_config,
+ )
ar.quantize()
with self.assertRaises(ValueError):
layer_config = {"model.decoder.layers.2.self_attn": {"bit": 2}} # should be bits
- ar = AutoRound("facebook/opt-125m", scheme="W3A16", nsamples=1, iters=1, layer_config=layer_config)
+ ar = AutoRound(
+ "/tf_dataset/auto_round/models/facebook/opt-125m",
+ scheme="W3A16",
+ nsamples=1,
+ iters=1,
+ layer_config=layer_config,
+ )
def test_quant_lm_head(self):
- model_name = "Qwen/Qwen3-8B"
+ model_name = "/tf_dataset/auto_round/models/Qwen/Qwen3-8B"
ar = AutoRound(model_name, quant_lm_head=True, iters=1, nsamples=1, seqlen=32)
ar.quantize()
diff --git a/test/test_cpu/test_autoround_acc.py b/test/test_cpu/test_autoround_acc.py
index 69133829c..97211ade4 100644
--- a/test/test_cpu/test_autoround_acc.py
+++ b/test/test_cpu/test_autoround_acc.py
@@ -37,7 +37,7 @@ class TestAutoRound(unittest.TestCase):
shutil.rmtree("runs", ignore_errors=True)
def test_default_acc(self):
- model_name = "hf-internal-testing/tiny-random-GPTJForCausalLM"
+ model_name = "/tf_dataset/auto_round/models/hf-internal-testing/tiny-random-GPTJForCausalLM"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float32, trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
bits, group_size, sym = 4, 128, True
@@ -76,7 +76,7 @@ class TestAutoRound(unittest.TestCase):
self.assertTrue(isclose(float(out0[0][0][0][0]), -0.021002087742090225, rel_tol=5e-04))
def test_3bits_asym_autoround(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
bits, sym = 3, False
autoround = AutoRound(model_name, bits=bits, sym=sym, iters=0)
diff --git a/test/test_cpu/test_autoround_export_to_itrex.py b/test/test_cpu/test_autoround_export_to_itrex.py
index 09db9f6d4..d9b4f42c6 100644
--- a/test/test_cpu/test_autoround_export_to_itrex.py
+++ b/test/test_cpu/test_autoround_export_to_itrex.py
@@ -35,14 +35,14 @@ class TestAutoroundExport(unittest.TestCase):
@classmethod
def setUpClass(self):
self.gptj = transformers.AutoModelForCausalLM.from_pretrained(
- "hf-internal-testing/tiny-random-GPTJForCausalLM",
+ "/tf_dataset/auto_round/models/hf-internal-testing/tiny-random-GPTJForCausalLM",
torchscript=True,
)
self.tokenizer = transformers.AutoTokenizer.from_pretrained(
- "hf-internal-testing/tiny-random-GPTJForCausalLM", trust_remote_code=True
+ "/tf_dataset/auto_round/models/hf-internal-testing/tiny-random-GPTJForCausalLM", trust_remote_code=True
)
self.gptj_no_jit = transformers.AutoModelForCausalLM.from_pretrained(
- "hf-internal-testing/tiny-random-GPTJForCausalLM",
+ "/tf_dataset/auto_round/models/hf-internal-testing/tiny-random-GPTJForCausalLM",
)
self.llm_dataloader = LLMDataLoader()
self.lm_input = torch.ones([1, 10], dtype=torch.long)
@@ -84,7 +84,7 @@ class TestAutoroundExport(unittest.TestCase):
def test_config(self):
from auto_round.export.export_to_itrex import QuantConfig
- config = QuantConfig.from_pretrained("TheBloke/Llama-2-7B-Chat-GPTQ")
+ config = QuantConfig.from_pretrained("/tf_dataset/auto_round/models/TheBloke/Llama-2-7B-Chat-GPTQ")
config.save_pretrained("quantization_config_dir")
loaded_config = QuantConfig.from_pretrained("quantization_config_dir")
self.assertEqual(config.group_size, loaded_config.group_size)
diff --git a/test/test_cpu/test_block_names.py b/test/test_cpu/test_block_names.py
index cf3506816..501caee25 100644
--- a/test/test_cpu/test_block_names.py
+++ b/test/test_cpu/test_block_names.py
@@ -119,7 +119,7 @@ class NestedMoEModel(nn.Module):
class TestQuantizationBlocks(unittest.TestCase):
@classmethod
def setUpClass(self):
- self.model_name = "MBZUAI/LaMini-GPT-124M"
+ self.model_name = "/tf_dataset/auto_round/models/MBZUAI/LaMini-GPT-124M"
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
self.llm_dataloader = LLMDataLoader()
@@ -196,7 +196,7 @@ class TestQuantizationBlocks(unittest.TestCase):
from auto_round.utils import get_block_names
- model_name = "Qwen/Qwen2-VL-2B-Instruct"
+ model_name = "/tf_dataset/auto_round/models/Qwen/Qwen2-VL-2B-Instruct"
model = Qwen2VLForConditionalGeneration.from_pretrained(model_name, trust_remote_code=True, device_map="auto")
block_name = get_block_names(model, quant_vision=True)
self.assertTrue(len(block_name) == 2)
@@ -208,7 +208,7 @@ class TestQuantizationBlocks(unittest.TestCase):
def test_moe(self):
from auto_round.utils import get_block_names
- model_name = "Qwen/Qwen1.5-MoE-A2.7B"
+ model_name = "/tf_dataset/auto_round/models/Qwen/Qwen1.5-MoE-A2.7B"
# config = AutoConfig.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
diff --git a/test/test_cpu/test_calib_dataset.py b/test/test_cpu/test_calib_dataset.py
index 6746ff69c..689cc705c 100644
--- a/test/test_cpu/test_calib_dataset.py
+++ b/test/test_cpu/test_calib_dataset.py
@@ -38,7 +38,7 @@ class TestLocalCalibDataset(unittest.TestCase):
json.dump(item, jsonl_file, ensure_ascii=False)
jsonl_file.write("\n")
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
self.model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
@@ -71,7 +71,7 @@ class TestLocalCalibDataset(unittest.TestCase):
autoround.quantize()
def test_apply_chat_template(self):
- model_name = "Qwen/Qwen2.5-0.5B-Instruct"
+ model_name = "/tf_dataset/auto_round/models/Qwen/Qwen2.5-0.5B-Instruct"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
dataset = "NeelNanda/pile-10k:apply_chat_template:system_prompt=''"
diff --git a/test/test_cpu/test_cli_usage.py b/test/test_cpu/test_cli_usage.py
index 1eed6d30e..2b93f5131 100644
--- a/test/test_cpu/test_cli_usage.py
+++ b/test/test_cpu/test_cli_usage.py
@@ -15,6 +15,8 @@ class TestAutoRoundCmd(unittest.TestCase):
def tearDownClass(self):
shutil.rmtree("./saved", ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
+ shutil.rmtree("../../saved", ignore_errors=True)
+ shutil.rmtree("../../tmp_autoround", ignore_errors=True)
def test_auto_round_cmd(self):
python_path = sys.executable
@@ -25,13 +27,13 @@ class TestAutoRoundCmd(unittest.TestCase):
assert False, "cmd line test fail, please have a check"
res = os.system(
- f"cd ../.. && {python_path} -m auto_round --model 'facebook/opt-125m' --seqlen 32 --iter 2 --nsamples 1 --format auto_gptq,auto_round --output_dir ./saved --tasks piqa"
+ f"cd ../.. && {python_path} -m auto_round --model '/tf_dataset/auto_round/models/facebook/opt-125m' --seqlen 32 --iter 2 --nsamples 1 --format auto_gptq,auto_round --output_dir ./saved --tasks piqa"
)
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
res = os.system(
- f"cd ../.. && {python_path} -m auto_round --model 'facebook/opt-125m' --seqlen 8 --iter 1 --nsamples 1 --eval_task_by_task --tasks openbookqa --bs 32"
+ f"cd ../.. && {python_path} -m auto_round --model '/tf_dataset/auto_round/models/facebook/opt-125m' --seqlen 8 --iter 1 --nsamples 1 --eval_task_by_task --tasks openbookqa --bs 32"
)
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
@@ -55,13 +57,13 @@ class TestAutoRoundCmd(unittest.TestCase):
assert False, "cmd line test fail, please have a check"
res = os.system(
- f"cd ../.. && {python_path} -m auto_round --mllm --model Qwen/Qwen2-VL-2B-Instruct --iter 2 --nsamples 2 --seqlen 32 --format auto_round --output_dir ./saved"
+ f"cd ../.. && {python_path} -m auto_round --mllm --model /tf_dataset/auto_round/models/Qwen/Qwen2-VL-2B-Instruct --iter 2 --nsamples 2 --seqlen 32 --format auto_round --output_dir ./saved"
)
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
res = os.system(
- f"cd ../.. && {python_path} -m auto_round --mllm --iter 2 --nsamples 2 --model Qwen/Qwen2-VL-2B-Instruct --seqlen 32 --format auto_round"
+ f"cd ../.. && {python_path} -m auto_round --mllm --iter 2 --nsamples 2 --model /tf_dataset/auto_round/models/Qwen/Qwen2-VL-2B-Instruct --seqlen 32 --format auto_round"
" --quant_nontext_module --output_dir ./saved "
)
if res > 0 or res == -1:
diff --git a/test/test_cpu/test_conv1d.py b/test/test_cpu/test_conv1d.py
index 25e695b40..edd28110f 100644
--- a/test/test_cpu/test_conv1d.py
+++ b/test/test_cpu/test_conv1d.py
@@ -23,7 +23,7 @@ class LLMDataLoader:
class TestQuantizationConv1d(unittest.TestCase):
@classmethod
def setUpClass(self):
- self.model_name = "MBZUAI/LaMini-GPT-124M"
+ self.model_name = "/tf_dataset/auto_round/models/MBZUAI/LaMini-GPT-124M"
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
self.llm_dataloader = LLMDataLoader()
diff --git a/test/test_cpu/test_export.py b/test/test_cpu/test_export.py
index aef11a30e..e162f0b80 100644
--- a/test/test_cpu/test_export.py
+++ b/test/test_cpu/test_export.py
@@ -35,7 +35,7 @@ class LLMDataLoader:
class TestAutoRound(unittest.TestCase):
@classmethod
def setUpClass(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
self.save_dir = "./saved"
self.model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
@@ -49,7 +49,7 @@ class TestAutoRound(unittest.TestCase):
def test_autogptq_format(self):
for group_size in [-1, 32, 128]:
bits, sym = 4, False
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
autoround = AutoRound(
model=model_name,
bits=bits,
@@ -79,7 +79,7 @@ class TestAutoRound(unittest.TestCase):
def test_autoround_format(self):
for group_size in [-1, 32, 128]:
bits, sym = 4, True
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
autoround = AutoRound(
model=model_name,
bits=bits,
@@ -105,7 +105,7 @@ class TestAutoRound(unittest.TestCase):
def test_autoround_awq_format(self):
for group_size in [-1, 32, 128]:
bits, sym = 4, False
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
autoround = AutoRound(
model=model_name,
bits=bits,
@@ -217,7 +217,7 @@ class TestAutoRound(unittest.TestCase):
from safetensors import safe_open
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
autoround = AutoRound(
model,
@@ -303,7 +303,7 @@ class TestAutoRound(unittest.TestCase):
shutil.rmtree(quantized_model_path, ignore_errors=True)
def test_mxfp4_llmcompressor_format(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
from transformers import AutoConfig
@@ -352,7 +352,7 @@ class TestAutoRound(unittest.TestCase):
shutil.rmtree("./saved", ignore_errors=True)
def test_rtn_mxfp4_llmcompressor_format(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
from transformers import AutoConfig
@@ -400,7 +400,7 @@ class TestAutoRound(unittest.TestCase):
shutil.rmtree("./saved", ignore_errors=True)
def test_mxfp8_llmcompressor_format(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
from transformers import AutoConfig
@@ -439,7 +439,7 @@ class TestAutoRound(unittest.TestCase):
shutil.rmtree("./saved", ignore_errors=True)
def test_nvfp4_llmcompressor_format(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
from transformers import AutoConfig
@@ -478,7 +478,7 @@ class TestAutoRound(unittest.TestCase):
shutil.rmtree("./saved", ignore_errors=True)
def test_nvfp4_autoround_format(self):
- model_name = "facebook/opt-125m"
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
from transformers import AutoConfig
diff --git a/test/test_cpu/test_generation.py b/test/test_cpu/test_generation.py
index d1e51f722..5018d1610 100644
--- a/test/test_cpu/test_generation.py
+++ b/test/test_cpu/test_generation.py
@@ -22,7 +22,7 @@ class LLMDataLoader:
class TestAutoRoundFormatGeneration(unittest.TestCase):
@classmethod
def setUpClass(self):
- self.model_name = "facebook/opt-125m"
+ self.model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
self.model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
self.llm_dataloader = LLMDataLoader()
diff --git a/test/test_cpu/test_gguf_format.py b/test/test_cpu/test_gguf_format.py
index 2a25b0f5f..96b489ffe 100644
--- a/test/test_cpu/test_gguf_format.py
+++ b/test/test_cpu/test_gguf_format.py
@@ -23,6 +23,7 @@ class LLMDataLoader:
class TestGGUF(unittest.TestCase):
@classmethod
def setUpClass(self):
+ self.model_name = "/tf_dataset/auto_round/models/Qwen/Qwen2.5-0.5B-Instruct"
self.model_name = "Qwen/Qwen2.5-0.5B-Instruct"
self.model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
@@ -36,7 +37,7 @@ class TestGGUF(unittest.TestCase):
def test_basic_usage(self):
python_path = sys.executable
res = os.system(
- f"cd ../.. && {python_path} -m auto_round --model benzart/gemma-2b-it-fine-tuning-for-code-test "
+ f"cd ../.. && {python_path} -m auto_round --model /tf_dataset/auto_round/models/benzart/gemma-2b-it-fine-tuning-for-code-test "
f" --bs 16 --iters 0 --nsamples 1 --format gguf:q4_k_m"
)
if res > 0 or res == -1:
@@ -196,7 +197,7 @@ class TestGGUF(unittest.TestCase):
# shutil.rmtree("./saved", ignore_errors=True)
def test_gguf_baseline(self):
- model_name = "Qwen/Qwen2.5-1.5B-Instruct"
+ model_name = "/tf_dataset/auto_round/models/Qwen/Qwen2.5-1.5B-Instruct"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
autoround = AutoRound(
model,
@@ -243,7 +244,7 @@ class TestGGUF(unittest.TestCase):
# shutil.rmtree("./saved", ignore_errors=True)
def test_q4_k_m(self):
- model_name = "Qwen/Qwen2.5-1.5B-Instruct"
+ model_name = "/tf_dataset/auto_round/models/Qwen/Qwen2.5-1.5B-Instruct"
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
layer_config = {
@@ -290,7 +291,7 @@ class TestGGUF(unittest.TestCase):
shutil.rmtree("./saved", ignore_errors=True)
def test_all_format(self):
- model_name = "Qwen/Qwen2.5-1.5B-Instruct"
+ model_name = "/tf_dataset/auto_round/models/Qwen/Qwen2.5-1.5B-Instruct"
python_path = sys.executable
# for gguf_format in ["gguf:q4_0", "gguf:q4_1", "gguf:q4_k_m", "gguf:q6_k"]:
for gguf_format in ["gguf:q4_k_m"]:
@@ -311,7 +312,7 @@ class TestGGUF(unittest.TestCase):
shutil.rmtree("../../tmp_autoround", ignore_errors=True)
def test_vlm_gguf(self):
- model_name = "Qwen/Qwen2-VL-2B-Instruct"
+ model_name = "/tf_dataset/auto_round/models/Qwen/Qwen2-VL-2B-Instruct"
from auto_round import AutoRoundMLLM
from auto_round.utils import mllm_load_model
diff --git a/test/test_cpu/test_llmcompressor.py b/test/test_cpu/test_llmcompressor.py
new file mode 100644
index 000000000..051dfb075
--- /dev/null
+++ b/test/test_cpu/test_llmcompressor.py
@@ -0,0 +1,93 @@
+import os
+import shutil
+import sys
+import unittest
+
+sys.path.insert(0, "../..")
+
+import torch
+from transformers import AutoModelForCausalLM, AutoTokenizer
+
+from auto_round import AutoRound
+
+
+class TestLLMC(unittest.TestCase):
+ @classmethod
+ def setUpClass(self):
+ self.model_name = "/tf_dataset/auto_round/models/stas/tiny-random-llama-2"
+ self.model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
+
+ @classmethod
+ def tearDownClass(self):
+ shutil.rmtree("./saved", ignore_errors=True)
+ shutil.rmtree("runs", ignore_errors=True)
+
+ def test_llmcompressor_w8a8(self):
+ bits, group_size, sym, act_bits = 8, -1, True, 8
+ ## quantize the model
+ autoround = AutoRound(
+ self.model,
+ self.tokenizer,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ act_bits=act_bits,
+ seqlen=8,
+ nsamples=2,
+ iters=0,
+ )
+ autoround.quantize()
+ autoround.save_quantized("./saved", format="llm_compressor", inplace=True)
+
+ def test_llmcompressor_fp8(self):
+ ## quantize the model
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
+ autoround = AutoRound(
+ model_name,
+ scheme="FP8_STATIC",
+ seqlen=8,
+ nsamples=2,
+ iters=0,
+ )
+ autoround.quantize_and_save("./saved", format="llm_compressor")
+ # from vllm import LLM
+ # model = LLM("./saved")
+ # result = model.generate("Hello my name is")
+ # print(result)
+
+ import json
+
+ config = json.load(open("./saved/config.json"))
+ self.assertIn("group_0", config["quantization_config"]["config_groups"])
+ self.assertEqual(config["quantization_config"]["config_groups"]["group_0"]["input_activations"]["num_bits"], 8)
+ self.assertEqual(config["quantization_config"]["config_groups"]["group_0"]["weights"]["strategy"], "channel")
+ self.assertEqual(config["quantization_config"]["quant_method"], "compressed-tensors")
+
+ def test_autoround_llmcompressor_fp8(self):
+ ## quantize the model
+ model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
+ autoround = AutoRound(
+ model_name,
+ scheme="FP8_STATIC",
+ seqlen=8,
+ group_size=0,
+ nsamples=2,
+ iters=0,
+ )
+ autoround.quantize_and_save("./saved", format="auto_round:llm_compressor")
+
+ import json
+
+ config = json.load(open("./saved/config.json"))
+ self.assertIn("group_0", config["quantization_config"]["config_groups"])
+ self.assertEqual(config["quantization_config"]["config_groups"]["group_0"]["input_activations"]["num_bits"], 8)
+ self.assertEqual(config["quantization_config"]["config_groups"]["group_0"]["weights"]["strategy"], "tensor")
+ self.assertEqual(
+ config["quantization_config"]["config_groups"]["group_0"]["input_activations"]["strategy"], "tensor"
+ )
+ self.assertEqual(config["quantization_config"]["quant_method"], "compressed-tensors")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test/test_cpu/test_llmcompressor_w8a8.py b/test/test_cpu/test_llmcompressor_w8a8.py
deleted file mode 100644
index b539ab5d0..000000000
--- a/test/test_cpu/test_llmcompressor_w8a8.py
+++ /dev/null
@@ -1,45 +0,0 @@
-import os
-import shutil
-import sys
-import unittest
-
-sys.path.insert(0, "../..")
-
-import torch
-from transformers import AutoModelForCausalLM, AutoTokenizer
-
-from auto_round import AutoRound
-
-
-class TestLLMC(unittest.TestCase):
- @classmethod
- def setUpClass(self):
- self.model_name = "stas/tiny-random-llama-2"
- self.model = AutoModelForCausalLM.from_pretrained(self.model_name, torch_dtype="auto", trust_remote_code=True)
- self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
-
- @classmethod
- def tearDownClass(self):
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- def test_llmcompressor_w8a8(self):
- bits, group_size, sym, act_bits = 8, -1, True, 8
- ## quantize the model
- autoround = AutoRound(
- self.model,
- self.tokenizer,
- bits=bits,
- group_size=group_size,
- sym=sym,
- act_bits=act_bits,
- seqlen=8,
- nsamples=2,
- iters=0,
- )
- autoround.quantize()
- autoround.save_quantized("./saved", format="llm_compressor", inplace=True)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/test/test_cpu/test_load_awq_gptq.py b/test/test_cpu/test_load_awq_gptq.py
index bda3d4447..4fb6bb977 100644
--- a/test/test_cpu/test_load_awq_gptq.py
+++ b/test/test_cpu/test_load_awq_gptq.py
@@ -38,7 +38,7 @@ class TestAutoRound(unittest.TestCase):
shutil.rmtree("runs", ignore_errors=True)
def test_load_gptq_no_dummy_gidx_model(self):
- model_name = "ModelCloud/Llama-3.2-1B-Instruct-gptqmodel-4bit-vortex-v1"
+ model_name = "/tf_dataset/auto_round/models/ModelCloud/Llama-3.2-1B-Instruct-gptqmodel-4bit-vortex-v1"
quantization_config = AutoRoundConfig()
with self.assertRaises(NotImplementedError) as cm:
model = AutoModelForCausalLM.from_pretrained(
@@ -50,7 +50,7 @@ class TestAutoRound(unittest.TestCase):
)
def test_load_awq(self):
- model_name = "casperhansen/opt-125m-awq"
+ model_name = "/tf_dataset/auto_round/models/casperhansen/opt-125m-awq"
quantization_config = AutoRoundConfig()
model = AutoModelForCausalLM.from_pretrained(
model_name,
diff --git a/test/test_cpu/test_low_cpu_mem.py b/test/test_cpu/test_low_cpu_mem.py
index 13eb34767..582b5e47b 100644
--- a/test/test_cpu/test_low_cpu_mem.py
+++ b/test/test_cpu/test_low_cpu_mem.py
@@ -30,7 +30,7 @@ class LLMDataLoader:
class TestLowCPUMem(unittest.TestCase):
@classmethod
def setUpClass(self):
- self.model_name = "facebook/opt-125m"
+ self.model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
self.saved_path = "./test_tmp_saved"
self.ori_model = AutoModelForCausalLM.from_pretrained(self.model_name, trust_remote_code=True)
self.model = load_model_with_hooks(
diff --git a/test/test_cpu/test_mllm.py b/test/test_cpu/test_mllm.py
index 10ccd9d37..8510adca5 100644
--- a/test/test_cpu/test_mllm.py
+++ b/test/test_cpu/test_mllm.py
@@ -30,7 +30,7 @@ class FakeDataLoader:
class TestAutoRoundMLLM(unittest.TestCase):
@classmethod
def setUpClass(self):
- self.model_name = "Qwen/Qwen2-VL-2B-Instruct"
+ self.model_name = "/tf_dataset/auto_round/models/Qwen/Qwen2-VL-2B-Instruct"
self.dataset = FakeDataLoader()
@classmethod
@@ -142,7 +142,9 @@ class TestAutoRoundMLLM(unittest.TestCase):
self.model_name, trust_remote_code=True, device_map="auto"
)
self.assertFalse(is_pure_text_model(model))
- model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m", trust_remote_code=True)
+ model = AutoModelForCausalLM.from_pretrained(
+ "/tf_dataset/auto_round/models/facebook/opt-125m", trust_remote_code=True
+ )
self.assertTrue(is_pure_text_model(model))
def test_str_input(self):
@@ -212,7 +214,7 @@ class TestAutoRoundMLLM(unittest.TestCase):
def test_qwen2_5(self):
from auto_round.utils import mllm_load_model
- model_name = "Qwen/Qwen2.5-VL-3B-Instruct"
+ model_name = "/tf_dataset/auto_round/models/Qwen/Qwen2.5-VL-3B-Instruct"
model, processor, tokenizer, image_processor = mllm_load_model(model_name)
autoround = AutoRoundMLLM(
model,
diff --git a/test/test_cpu/test_scheme.py b/test/test_cpu/test_scheme.py
index 55d044331..b59f88f4b 100644
--- a/test/test_cpu/test_scheme.py
+++ b/test/test_cpu/test_scheme.py
@@ -21,7 +21,7 @@ class LLMDataLoader:
class TestAutoRound(unittest.TestCase):
@classmethod
def setUpClass(self):
- self.model_name = "facebook/opt-125m"
+ self.model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
self.save_folder = "./saved"
self.llm_dataloader = LLMDataLoader()
@@ -31,7 +31,14 @@ class TestAutoRound(unittest.TestCase):
shutil.rmtree("runs", ignore_errors=True)
def test_gguf(self):
- ar = AutoRound("Qwen/Qwen3-0.6B", scheme="W2A16", nsamples=1, iters=1, seqlen=2, dataset=self.llm_dataloader)
+ ar = AutoRound(
+ "/tf_dataset/auto_round/models/Qwen/Qwen3-0.6B",
+ scheme="W2A16",
+ nsamples=1,
+ iters=1,
+ seqlen=2,
+ dataset=self.llm_dataloader,
+ )
ar.quantize_and_save(self.save_folder, format="gguf:q4_k_m")
self.assertEqual(ar.bits, 4)
shutil.rmtree(self.save_folder, ignore_errors=True)
@@ -57,7 +64,9 @@ class TestAutoRound(unittest.TestCase):
def test_vllm(self):
from auto_round import AutoRoundMLLM
- ar = AutoRoundMLLM("Qwen/Qwen2-VL-2B-Instruct", scheme="W2A16", nsamples=1, iters=1, seqlen=2)
+ ar = AutoRoundMLLM(
+ "/tf_dataset/auto_round/models/Qwen/Qwen2-VL-2B-Instruct", scheme="W2A16", nsamples=1, iters=1, seqlen=2
+ )
self.assertEqual(ar.bits, 2)
self.assertEqual(ar.act_bits, 16)
@@ -76,7 +85,7 @@ class TestAutoRound(unittest.TestCase):
"model.decoder.layers.4.self_attn.k_proj": QuantizationScheme.from_dict({"group_size": 64}),
}
ar = AutoRound(
- self.model_name,
+ "/tf_dataset/auto_round/models/facebook/opt-125m",
scheme="W3A16",
nsamples=1,
iters=1,
diff --git a/test/test_cpu/test_torch_backend.py b/test/test_cpu/test_torch_backend.py
index c12925fc4..557bf1f38 100644
--- a/test/test_cpu/test_torch_backend.py
+++ b/test/test_cpu/test_torch_backend.py
@@ -27,7 +27,7 @@ class TestAutoRoundTorchBackend(unittest.TestCase):
@classmethod
def setUpClass(self):
- self.model_name = "facebook/opt-125m"
+ self.model_name = "/tf_dataset/auto_round/models/facebook/opt-125m"
self.save_folder = "./saved"
self.llm_dataloader = LLMDataLoader()