Skip to content

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

Remove itrex format (#1301)

Tang Kaihui46f886065a44
diff --git a/auto_round/export/export_to_itrex/__init__.py b/auto_round/export/export_to_itrex/__init__.py
deleted file mode 100644
index a6c225a0c..000000000
--- a/auto_round/export/export_to_itrex/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright (c) 2023 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.
-from .export import save_quantized_as_itrex, pack_model
-from .config import QuantConfig
diff --git a/auto_round/export/export_to_itrex/bit_packer.py b/auto_round/export/export_to_itrex/bit_packer.py
deleted file mode 100644
index d3f323a6c..000000000
--- a/auto_round/export/export_to_itrex/bit_packer.py
+++ /dev/null
@@ -1,282 +0,0 @@
-# Copyright (c) 2024 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.
-"""Utility functions for bit packing."""
-
-
-from typing import Callable, Dict, Tuple
-
-try:
- import numba
-except ImportError:
- raise ImportError("Numba is required to use bit_packer module. Please install numba with `pip install numba`.")
-import numpy as np
-
-# key: (bits, compress_bits), value: pack function
-bit_packers: Dict[Tuple[int, int], Callable] = {}
-
-
-def register_pack_func(orig_bits: int, compress_bits: int):
- """Register the pack function."""
-
- def decorator(func):
- bit_packers[(orig_bits, compress_bits)] = func
- return func
-
- return decorator
-
-
-@register_pack_func(4, 32)
[email protected](nopython=True, parallel=True)
-def pack_array_with_numba_b4_c32(
- raw_array: np.ndarray, packed_array: np.ndarray, n_pack: int, new_in_features: int
-) -> np.ndarray:
- """Pack the array with numba when bits=4 and compress_bits=32."""
- for i in range(new_in_features):
- packed_array[:, i] = (
- ((raw_array[:, i * n_pack + 7] & 0b1111) << 28)
- | ((raw_array[:, i * n_pack + 6] & 0b1111) << 24)
- | ((raw_array[:, i * n_pack + 5] & 0b1111) << 20)
- | ((raw_array[:, i * n_pack + 4] & 0b1111) << 16)
- | ((raw_array[:, i * n_pack + 3] & 0b1111) << 12)
- | ((raw_array[:, i * n_pack + 2] & 0b1111) << 8)
- | ((raw_array[:, i * n_pack + 1] & 0b1111) << 4)
- | (raw_array[:, i * n_pack] & 0b1111)
- )
- return packed_array
-
-
-@register_pack_func(4, 16)
[email protected](nopython=True, parallel=True)
-def pack_array_with_numba_b4_c16(
- raw_array: np.ndarray, packed_array: np.ndarray, n_pack: int, new_in_features: int
-) -> np.ndarray:
- """Pack the array with numba when bits=4 and compress_bits=16."""
- for i in range(new_in_features):
- packed_array[:, i] = (
- ((raw_array[:, i * n_pack + 3] & 0b1111) << 12)
- | ((raw_array[:, i * n_pack + 2] & 0b1111) << 8)
- | ((raw_array[:, i * n_pack + 1] & 0b1111) << 4)
- | (raw_array[:, i * n_pack] & 0b1111)
- )
- return packed_array
-
-
-@register_pack_func(4, 8)
[email protected](nopython=True, parallel=True)
-def pack_array_with_numba_b4_c8(
- raw_array: np.ndarray, packed_array: np.ndarray, n_pack: int, new_in_features: int
-) -> np.ndarray:
- """Pack the array with numba when bits=4 and compress_bits=8."""
- for i in range(new_in_features):
- packed_array[:, i] = ((raw_array[:, i * n_pack + 1] & 0b1111) << 4) | (raw_array[:, i * n_pack] & 0b1111)
- return packed_array
-
-
-@register_pack_func(4, 64)
[email protected](nopython=True, parallel=True)
-def pack_array_with_numba_b4_c64(
- raw_array: np.ndarray, packed_array: np.ndarray, n_pack: int, new_in_features: int
-) -> np.ndarray:
- """Pack the array with numba when bits=4 and compress_bits=64."""
- for i in range(new_in_features):
- packed_array[:, i] = (
- ((raw_array[:, i * n_pack + 15] & 0b1111) << 60)
- | ((raw_array[:, i * n_pack + 14] & 0b1111) << 56)
- | ((raw_array[:, i * n_pack + 13] & 0b1111) << 52)
- | ((raw_array[:, i * n_pack + 12] & 0b1111) << 48)
- | ((raw_array[:, i * n_pack + 11] & 0b1111) << 44)
- | ((raw_array[:, i * n_pack + 10] & 0b1111) << 40)
- | ((raw_array[:, i * n_pack + 9] & 0b1111) << 36)
- | ((raw_array[:, i * n_pack + 8] & 0b1111) << 32)
- | ((raw_array[:, i * n_pack + 7] & 0b1111) << 28)
- | ((raw_array[:, i * n_pack + 6] & 0b1111) << 24)
- | ((raw_array[:, i * n_pack + 5] & 0b1111) << 20)
- | ((raw_array[:, i * n_pack + 4] & 0b1111) << 16)
- | ((raw_array[:, i * n_pack + 3] & 0b1111) << 12)
- | ((raw_array[:, i * n_pack + 2] & 0b1111) << 8)
- | ((raw_array[:, i * n_pack + 1] & 0b1111) << 4)
- | (raw_array[:, i * n_pack] & 0b1111)
- )
- return packed_array
-
-
-@register_pack_func(8, 32)
[email protected](nopython=True, parallel=True)
-def pack_array_with_numba_b8_c32(
- raw_array: np.ndarray, packed_array: np.ndarray, n_pack: int, new_in_features: int
-) -> np.ndarray:
- """Pack the array with numba when bits=8 and compress_bits=32."""
- for i in range(new_in_features):
- packed_array[:, i] = (
- ((raw_array[:, i * n_pack + 3] & 0b11111111) << 24)
- | ((raw_array[:, i * n_pack + 2] & 0b11111111) << 16)
- | ((raw_array[:, i * n_pack + 1] & 0b11111111) << 8)
- | (raw_array[:, i * n_pack] & 0b11111111)
- )
- return packed_array
-
-
-@register_pack_func(8, 16)
[email protected](nopython=True, parallel=True)
-def pack_array_with_numba_b8_c16(
- raw_array: np.ndarray, packed_array: np.ndarray, n_pack: int, new_in_features: int
-) -> np.ndarray:
- """Pack the array with numba when bits=8 and compress_bits=16."""
- for i in range(new_in_features):
- packed_array[:, i] = (
- ((raw_array[:, i * n_pack + 3] & 0b11111111) << 24)
- | ((raw_array[:, i * n_pack + 2] & 0b11111111) << 16)
- | ((raw_array[:, i * n_pack + 1] & 0b11111111) << 8)
- | (raw_array[:, i * n_pack] & 0b11111111)
- )
- return packed_array
-
-
-@register_pack_func(8, 8)
[email protected](nopython=True, parallel=True)
-def pack_array_with_numba_b8_c8(
- raw_array: np.ndarray, packed_array: np.ndarray, n_pack: int, new_in_features: int
-) -> np.ndarray:
- """Pack the array with numba when bits=8 and compress_bits=8."""
- for i in range(new_in_features):
- packed_array[:, i] = raw_array[:, i * n_pack] & 0b11111111
- return packed_array
-
-
-@register_pack_func(8, 64)
[email protected](nopython=True, parallel=True)
-def pack_array_with_numba_b8_c64(
- raw_array: np.ndarray, packed_array: np.ndarray, n_pack: int, new_in_features: int
-) -> np.ndarray:
- """Pack the array with numba when bits=8 and compress_bits=64."""
- for i in range(new_in_features):
- packed_array[:, i] = (
- ((raw_array[:, i * n_pack + 7] & 0b11111111) << 56)
- | ((raw_array[:, i * n_pack + 6] & 0b11111111) << 48)
- | ((raw_array[:, i * n_pack + 5] & 0b11111111) << 40)
- | ((raw_array[:, i * n_pack + 4] & 0b11111111) << 32)
- | ((raw_array[:, i * n_pack + 3] & 0b11111111) << 24)
- | ((raw_array[:, i * n_pack + 2] & 0b11111111) << 16)
- | ((raw_array[:, i * n_pack + 1] & 0b11111111) << 8)
- | (raw_array[:, i * n_pack] & 0b11111111)
- )
- return packed_array
-
-
-@register_pack_func(2, 32)
[email protected](nopython=True, parallel=True)
-def pack_array_with_numba_b2_c32(
- raw_array: np.ndarray, packed_array: np.ndarray, n_pack: int, new_in_features: int
-) -> np.ndarray:
- """Pack the array with numba when bits=2 and compress_bits=32."""
- for i in range(new_in_features):
- packed_array[:, i] = (
- ((raw_array[:, i * n_pack + 15] & 0b11) << 30)
- | ((raw_array[:, i * n_pack + 14] & 0b11) << 28)
- | ((raw_array[:, i * n_pack + 13] & 0b11) << 26)
- | ((raw_array[:, i * n_pack + 12] & 0b11) << 24)
- | ((raw_array[:, i * n_pack + 11] & 0b11) << 22)
- | ((raw_array[:, i * n_pack + 10] & 0b11) << 20)
- | ((raw_array[:, i * n_pack + 9] & 0b11) << 18)
- | ((raw_array[:, i * n_pack + 8] & 0b11) << 16)
- | ((raw_array[:, i * n_pack + 7] & 0b11) << 14)
- | ((raw_array[:, i * n_pack + 6] & 0b11) << 12)
- | ((raw_array[:, i * n_pack + 5] & 0b11) << 10)
- | ((raw_array[:, i * n_pack + 4] & 0b11) << 8)
- | ((raw_array[:, i * n_pack + 3] & 0b11) << 6)
- | ((raw_array[:, i * n_pack + 2] & 0b11) << 4)
- | ((raw_array[:, i * n_pack + 1] & 0b11) << 2)
- | (raw_array[:, i * n_pack] & 0b11)
- )
- return packed_array
-
-
-@register_pack_func(2, 16)
[email protected](nopython=True, parallel=True)
-def pack_array_with_numba_b2_c16(
- raw_array: np.ndarray, packed_array: np.ndarray, n_pack: int, new_in_features: int
-) -> np.ndarray:
- """Pack the array with numba when bits=2 and compress_bits=16."""
- for i in range(new_in_features):
- packed_array[:, i] = (
- ((raw_array[:, i * n_pack + 7] & 0b11) << 14)
- | ((raw_array[:, i * n_pack + 6] & 0b11) << 12)
- | ((raw_array[:, i * n_pack + 5] & 0b11) << 10)
- | ((raw_array[:, i * n_pack + 4] & 0b11) << 8)
- | ((raw_array[:, i * n_pack + 3] & 0b11) << 6)
- | ((raw_array[:, i * n_pack + 2] & 0b11) << 4)
- | ((raw_array[:, i * n_pack + 1] & 0b11) << 2)
- | (raw_array[:, i * n_pack] & 0b11)
- )
- return packed_array
-
-
-@register_pack_func(2, 8)
[email protected](nopython=True, parallel=True)
-def pack_array_with_numba_b2_c8(
- raw_array: np.ndarray, packed_array: np.ndarray, n_pack: int, new_in_features: int
-) -> np.ndarray:
- """Pack the array with numba when bits=2 and compress_bits=8."""
- for i in range(new_in_features):
- packed_array[:, i] = (
- ((raw_array[:, i * n_pack + 3] & 0b11) << 6)
- | ((raw_array[:, i * n_pack + 2] & 0b11) << 4)
- | ((raw_array[:, i * n_pack + 1] & 0b11) << 2)
- | (raw_array[:, i * n_pack] & 0b11)
- )
- return packed_array
-
-
-@register_pack_func(2, 64)
[email protected](nopython=True, parallel=True)
-def pack_array_with_numba_b2_c64(
- raw_array: np.ndarray, packed_array: np.ndarray, n_pack: int, new_in_features: int
-) -> np.ndarray:
- """Pack the array with numba when bits=2 and compress_bits=64."""
- for i in range(new_in_features):
- packed_array[:, i] = (
- ((raw_array[:, i * n_pack + 31] & 0b11) << 62)
- | ((raw_array[:, i * n_pack + 30] & 0b11) << 60)
- | ((raw_array[:, i * n_pack + 29] & 0b11) << 58)
- | ((raw_array[:, i * n_pack + 28] & 0b11) << 56)
- | ((raw_array[:, i * n_pack + 27] & 0b11) << 54)
- | ((raw_array[:, i * n_pack + 26] & 0b11) << 52)
- | ((raw_array[:, i * n_pack + 25] & 0b11) << 50)
- | ((raw_array[:, i * n_pack + 24] & 0b11) << 48)
- | ((raw_array[:, i * n_pack + 23] & 0b11) << 46)
- | ((raw_array[:, i * n_pack + 22] & 0b11) << 44)
- | ((raw_array[:, i * n_pack + 21] & 0b11) << 42)
- | ((raw_array[:, i * n_pack + 20] & 0b11) << 40)
- | ((raw_array[:, i * n_pack + 19] & 0b11) << 38)
- | ((raw_array[:, i * n_pack + 18] & 0b11) << 36)
- | ((raw_array[:, i * n_pack + 17] & 0b11) << 34)
- | ((raw_array[:, i * n_pack + 16] & 0b11) << 32)
- | ((raw_array[:, i * n_pack + 15] & 0b11) << 30)
- | ((raw_array[:, i * n_pack + 14] & 0b11) << 28)
- | ((raw_array[:, i * n_pack + 13] & 0b11) << 26)
- | ((raw_array[:, i * n_pack + 12] & 0b11) << 24)
- | ((raw_array[:, i * n_pack + 11] & 0b11) << 22)
- | ((raw_array[:, i * n_pack + 10] & 0b11) << 20)
- | ((raw_array[:, i * n_pack + 9] & 0b11) << 18)
- | ((raw_array[:, i * n_pack + 8] & 0b11) << 16)
- | ((raw_array[:, i * n_pack + 7] & 0b11) << 14)
- | ((raw_array[:, i * n_pack + 6] & 0b11) << 12)
- | ((raw_array[:, i * n_pack + 5] & 0b11) << 10)
- | ((raw_array[:, i * n_pack + 4] & 0b11) << 8)
- | ((raw_array[:, i * n_pack + 3] & 0b11) << 6)
- | ((raw_array[:, i * n_pack + 2] & 0b11) << 4)
- | ((raw_array[:, i * n_pack + 1] & 0b11) << 2)
- | (raw_array[:, i * n_pack] & 0b11)
- )
- return packed_array
diff --git a/auto_round/export/export_to_itrex/config.py b/auto_round/export/export_to_itrex/config.py
deleted file mode 100644
index 81c244140..000000000
--- a/auto_round/export/export_to_itrex/config.py
+++ /dev/null
@@ -1,303 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2023 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.
-"""Configs for Autoround quantization."""
-
-import copy
-import json
-import os
-from dataclasses import dataclass, field
-from typing import Any, Dict, Tuple, Union
-
-import torch
-from transformers import PretrainedConfig
-
-from auto_round.utils import convert_dtype_str2torch, convert_dtype_torch2str, logger
-
-QUANT_CONFIG = "quantize_config.json"
-
-
-class QuantConfig(PretrainedConfig):
- """A brief quantization configuration for reference when performing model de-quantization."""
-
- def __init__(
- self,
- bits=4,
- scale_dtype="fp32",
- group_size=128,
- sym=False,
- quant_method="autoround",
- model_name_or_path=None,
- model_file_base_name="model",
- enable_minmax_tuning=True,
- iters=1000,
- lr=0.001,
- minmax_lr=0.001,
- enable_quanted_input=True,
- compute_dtype=None,
- **kwargs,
- ):
- self.bits = bits
- self.group_size = group_size
- self.scale_dtype = convert_dtype_torch2str(scale_dtype)
- self.sym = sym
- self.quant_method = quant_method
- self.model_name_or_path = model_name_or_path
- self.model_file_base_name = model_file_base_name
- self.enable_minmax_tuning = enable_minmax_tuning
- self.iters = iters
- self.lr = lr
- self.minmax_lr = minmax_lr
- self.enable_quanted_input = enable_quanted_input
- self.compute_dtype = convert_dtype_torch2str(compute_dtype)
-
- if "export_to_xpu" not in kwargs or not kwargs["export_to_xpu"]:
- ### Redundant parameters, will be removed later. ###
- self.damp_percent = 0.01
- self.desc_act = False
- self.true_sequential = False
- self.quant_method = "gptq"
- else:
- ### XPU special parameters. ###
- self.weight_dtype = "int4_fullrange" # Due to ipex format limitations. Actually, it's int4_clip.
-
- def post_init(self):
- r"""Safety checker for CPU that arguments are correct
- also replaces some NoneType arguments with their default values."""
-
- if self.scale_dtype not in ["fp32", "fp16", "bf16"]:
- raise ValueError("scale_dtype must be 'fp32', 'fp16' or 'bf16'.")
-
- if self.group_size not in [-1, 32, 128]:
- raise ValueError("group_size must be an integer in [-1, 32, 128]")
-
- def post_init_xpu(self):
- r"""
- Safety checker for XPU that arguments are correct
- - also replaces some NoneType arguments with their default values.
- """
-
- if self.compute_dtype is not None and self.compute_dtype not in ["fp16"]:
- raise ValueError("compute_dtype must be 'fp16'.")
- elif self.compute_dtype is None:
- self.compute_dtype = "fp16"
-
- if self.bits is None:
- self.bits = 4
- elif self.bits not in [4]:
- raise ValueError(f"Only support quantization to [4] bits but found {self.bits}")
-
- if self.weight_dtype is None:
- self.weight_dtype = "int4_fullrange"
-
- elif self.weight_dtype not in [
- "int4_fullrange",
- ]:
- raise ValueError(f"weight_dtype must be a string in 'int4_fullrange', but get {self.weight_dtype}.")
-
- if self.scale_dtype is not None and self.scale_dtype not in ["fp16"]:
- raise ValueError("scale_dtype must be a string in 'fp16'")
- elif self.scale_dtype is None:
- self.scale_dtype = "fp16"
-
- # if not isinstance(self.use_double_quant, bool):
- # raise ValueError("use_double_quant must be a boolean")
-
- # if self.use_double_quant and not isinstance(self.double_quant_dtype, str):
- # raise ValueError("double_quant_dtype must be a string")
-
- # if self.use_double_quant and not isinstance(self.scale_dtype, str):
- # raise ValueError("scale_dtype must be a string")
-
- if not isinstance(self.group_size, int):
- raise ValueError("group_size must be a int")
-
- if self.sym is not True:
- raise ValueError("asym is not support, only support 'sym' now!")
- self.use_neural_speed = False
-
- def quantization_method(self):
- r"""This method returns the quantization method used for the model."""
- return self.quant_method
-
- @classmethod
- def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
- """Instantiates a [`QuantConfig`] from a Python dictionary of parameters.
-
- Args:
- config_dict (`Dict[str, Any]`):
- Dictionary that will be used to instantiate the configuration object.
- return_unused_kwargs (`bool`):
- Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
- `PreTrainedModel`.
- kwargs (`Dict[str, Any]`):
- Additional parameters from which to initialize the configuration object.
- Returns:
- [`QuantConfig`]: The configuration object instantiated from those parameters.
- """
-
- config = cls(**config_dict)
-
- to_remove = []
- for key, value in kwargs.items():
- if hasattr(config, key):
- setattr(config, key, value)
- to_remove.append(key)
- for key in to_remove:
- kwargs.pop(key, None)
-
- if return_unused_kwargs:
- return config, kwargs
- else:
- return config
-
- @classmethod
- def from_json_file(cls, json_file_path, return_unused_kwargs, **kwargs):
- with open(json_file_path, "r", encoding="utf-8") as f:
- config_dict = json.load(f)
- return cls.from_dict(config_dict, return_unused_kwargs, **kwargs)
-
- def to_json_file(self, json_file_path: Union[str, os.PathLike], use_diff: bool = True):
- """Save this instance to a JSON file.
-
- Args:
- json_file_path (`str` or `os.PathLike`):
- Path to the JSON file in which this configuration instance's parameters will be saved.
- """
- with open(json_file_path, "w", encoding="utf-8") as writer:
- writer.write(self.to_json_string(use_diff=use_diff))
-
- def to_dict(self) -> Dict[str, Any]:
- """Serializes this instance to a Python dictionary.
-
- Returns:
- `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
- """
-
- output = copy.deepcopy(self.__dict__)
- return output
-
- def __repr__(self):
- return f"{self.__class__.__name__} {self.to_json_string()}"
-
- def to_json_string(self, use_diff: bool = True) -> str:
- """Serializes this instance to a JSON string.
-
- Args:
- use_diff (`bool`, *optional*, defaults to `True`):
- If set to `True`, only the difference between the config instance and the default
- `QuantConfig()`
- is serialized to JSON string.
- Returns:
- `str`: String containing all the attributes that make up this configuration instance in JSON format.
- """
- if use_diff is True:
- config_dict = self.to_diff_dict()
- else:
- config_dict = self.to_dict()
-
- return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
-
- def to_diff_dict(self) -> Dict[str, Any]:
- """Removes all attributes from config which correspond to the default config attributes
- for better readability and serializes to a Python dictionary.
-
- Returns:
- `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
- """
- config_dict = self.to_dict()
-
- # get the default config dict
- default_config_dict = QuantConfig().to_dict()
-
- serializable_config_dict = {}
-
- # only serialize values that differ from the default config
- for key, value in config_dict.items():
- if value != default_config_dict[key]:
- serializable_config_dict[key] = value
-
- return serializable_config_dict
-
- def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
- """Save a configuration object to the directory `save_directory`, so that it can be re-loaded using the
- [`~PretrainedConfig.from_pretrained`] class method.
-
- Args:
- save_directory (`str` or `os.PathLike`):
- Directory where the configuration JSON file will be saved (will be created if it does not exist).
- push_to_hub (`bool`, *optional*, defaults to `False`):
- Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
- repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
- namespace).
- kwargs (`Dict[str, Any]`, *optional*):
- Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
- """
- self._set_token_in_kwargs(kwargs)
-
- if os.path.isfile(save_directory):
- raise OSError(f"Provided path ({save_directory}) should be a directory, not a file")
-
- os.makedirs(save_directory, exist_ok=True)
-
- if push_to_hub:
- commit_message = kwargs.pop("commit_message", None)
- repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
- repo_id = self._create_repo(repo_id, **kwargs)
- files_timestamps = self._get_files_timestamps(save_directory)
-
- # If we save using the predefined names, we can load using `from_pretrained`
- output_config_file = os.path.join(save_directory, QUANT_CONFIG)
-
- self.to_json_file(output_config_file, use_diff=False)
- logger.info(f"Configuration saved in {output_config_file}")
-
- if push_to_hub:
- self._upload_modified_files(
- save_directory,
- repo_id,
- files_timestamps,
- commit_message=commit_message,
- token=kwargs.get("token", None),
- )
-
- @classmethod
- def get_config_dict(
- cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
- ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
- return super().get_config_dict(pretrained_model_name_or_path, _configuration_file=QUANT_CONFIG, **kwargs)
-
- def remove_redundant_parameters(self):
- remove_parameters = [
- "calib_dataloader",
- "dataset",
- "scheme",
- "tokenizer",
- "use_neural_speed",
- "enable_quanted_input",
- "layer_wise",
- "nsamples",
- "lr",
- "minmax_lr",
- "iters",
- "enable_quanted_input",
- "model_file_base_name",
- "enable_minmax_tuning",
- "model_name_or_path",
- ]
- for parameter in remove_parameters:
- if hasattr(self, parameter):
- delattr(self, parameter)
diff --git a/auto_round/export/export_to_itrex/export.py b/auto_round/export/export_to_itrex/export.py
deleted file mode 100644
index 280a83561..000000000
--- a/auto_round/export/export_to_itrex/export.py
+++ /dev/null
@@ -1,278 +0,0 @@
-# Copyright (c) 2023 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
-from typing import Callable, Dict, List, Optional, Union
-
-import torch
-import transformers
-
-from auto_round.logger import logger
-from auto_round.utils import check_to_quantized, detect_device, get_module, set_module
-
-from .config import QuantConfig
-from .model_wrapper import WeightOnlyLinear
-
-
-def quant_weight_w_scale(weight, scale, zp, group_size=-1, device="cpu"):
- """Quant and dequant tensor with group size.
-
- Args:
- weight: input weight
- scale: scale
- zp: zero point
- group_size (int, optional): how many elements share one scale/zp. Defaults to -1.
-
- Returns:
- output: int weight.
- """
- scale = scale.to(device)
- if zp is not None and isinstance(zp, torch.Tensor):
- zp = zp.to(device)
- if group_size == -1:
- return torch.round(weight / scale) if zp is None else torch.round(weight / scale + zp)
- int_weight = torch.zeros(weight.shape).to(device)
- leng = weight.shape[1] // group_size
- tail_flag = False if weight.shape[1] % group_size == 0 else True
- for i in range(leng):
- int_weight_tmp = weight[:, i * group_size : (i + 1) * group_size] / scale[:, i].unsqueeze(1)
- if zp is not None:
- int_weight_tmp += zp[:, i].unsqueeze(1)
- int_weight[:, i * group_size : (i + 1) * group_size] = torch.round(int_weight_tmp)
- if tail_flag:
- int_weight_tmp = weight[:, leng * group_size :] / scale[:, -1].unsqueeze(1)
- if zp is not None:
- int_weight_tmp += zp[:, -1].unsqueeze(1)
- int_weight[:, leng * group_size :] = torch.round(int_weight_tmp)
- return int_weight
-
-
-def save_quantized_as_itrex(
- output_dir: str,
- model: torch.nn.Module = None,
- tokenizer: Callable = None,
- layer_config: dict = None,
- inplace: bool = True,
- device: Union[str, torch.device] = "cpu",
- serialization_dict: dict = None,
- **kwargs,
-) -> torch.nn.Module:
- """Save configure file and weights for CPU backend inference."""
- sym = serialization_dict["sym"]
- bits = serialization_dict["bits"]
- group_size = serialization_dict["group_size"]
- iters = serialization_dict["iters"]
- lr = serialization_dict["lr"]
- minmax_lr = serialization_dict["minmax_lr"]
- enable_minmax_tuning = serialization_dict["enable_minmax_tuning"]
- enable_quanted_input = serialization_dict["enable_quanted_input"]
- scale_dtype = serialization_dict["scale_dtype"]
- safe_serialization = True if "safe_serialization" not in kwargs.keys() else kwargs["safe_serialization"]
-
- processor = kwargs.get("processor", None)
- image_processor = kwargs.get("image_processor", None)
-
- compressed_model = pack_model(model, layer_config, inplace=inplace, device=device)
- if output_dir is None:
- return compressed_model
- quantize_config = QuantConfig(
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=iters,
- lr=lr,
- minmax_lr=minmax_lr,
- enable_minmax_tuning=enable_minmax_tuning,
- enable_quanted_input=enable_quanted_input,
- scale_dtype=scale_dtype,
- )
- if quantize_config is not None:
- quantize_config.post_init()
- config = compressed_model.config
- setattr(config, "quantization_config", quantize_config.to_dict())
- config.save_pretrained(output_dir)
- quantize_config.save_pretrained(output_dir)
- try:
- compressed_model.save_pretrained(output_dir, safe_serialization=safe_serialization)
- if tokenizer is not None and hasattr(tokenizer, "save_pretrained"):
- 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)
- logger.info("Saved config file and weights of quantized model to {}.".format(output_dir))
- except IOError as e: # pragma: no cover
- logger.error("Fail to save configure file and weights due to {}.".format(e))
- return compressed_model
-
-
-def save_quantized_as_itrex_xpu(
- output_dir: str,
- model: torch.nn.Module = None,
- tokenizer: Callable = None,
- layer_config: dict = None,
- inplace: bool = True,
- device: Union[str, torch.device] = "cpu",
- serialization_dict: dict = None,
- **kwargs,
-) -> torch.nn.Module:
- """Save configure file and weights for XPU backend inference."""
- sym = serialization_dict["sym"]
- bits = serialization_dict["bits"]
- group_size = serialization_dict["group_size"]
- iters = serialization_dict["iters"]
- lr = serialization_dict["lr"]
- minmax_lr = serialization_dict["minmax_lr"]
- enable_minmax_tuning = serialization_dict["enable_minmax_tuning"]
- enable_quanted_input = serialization_dict["enable_quanted_input"]
- scale_dtype = serialization_dict["scale_dtype"]
-
- processor = kwargs.get("processor", None)
- image_processor = kwargs.get("image_processor", None)
-
- compressed_model = pack_model(inplace=inplace, **kwargs)
- if output_dir is None:
- return compressed_model
- quantize_config = QuantConfig(
- bits=bits,
- group_size=group_size,
- sym=sym,
- iters=iters,
- lr=lr,
- minmax_lr=minmax_lr,
- enable_minmax_tuning=enable_minmax_tuning,
- enable_quanted_input=enable_quanted_input,
- scale_dtype=scale_dtype,
- export_to_xpu=True,
- )
- if quantize_config is not None:
- quantize_config.post_init_xpu()
- quantize_config.remove_redundant_parameters()
- config = compressed_model.config
- setattr(config, "quantization_config", quantize_config.to_dict())
- config.save_pretrained(output_dir)
- quantize_config.save_pretrained(output_dir)
- try:
- compressed_model.save_pretrained(output_dir, safe_serialization=True)
- 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)
- logger.info("Saved config file and weights of quantized model to {}.".format(output_dir))
- except IOError as e: # pragma: no cover
- logger.error("Fail to save configure file and weights due to {}.".format(e))
- return compressed_model
-
-
-def pack_model(
- model,
- layer_config: Union[str, dict],
- enable_full_range=False,
- compression_dtype=torch.int32,
- compression_dim=1,
- device="cpu",
- use_optimum_format=True,
- inplace=False,
- **kwargs,
-):
- """Convert Linear to WeightOnlyLinear for low memory inference.
-
- Args:
- layer_config (str|dict): qconfig dict or Path of qconfig.json.
- enable_full_range (bool, optional): Whether to leverage the full compression range
- under symmetric quantization. Defaults to False.
- compression_dtype (torch.Tensor, optional): The target dtype after comoression.
- Defaults to torch.int32.
- compression_dim (int, optional): Select from [0, 1], 0 is output channel,
- 1 is input channel. Defaults to 1.
- device (str, optional): choose device for compression. Defaults to cpu.
- use_optimum_format (bool, optional): use the popular huggingface compression format.
- 1: compression_dim: weight = 1, zeros = 0 and both are transposed.
- 2: zeros -= 1 before compression. Why we need it?
- 3: g_idx: use same number for one group instead of recording the channel order.
- 4. parameter name changed, such as 'packed_weight' -> 'qweight'.
- 5. zeros is always needed even for sym.
- inplace (bool, optional): Compress the model in place, or copy the model and compress it.
-
- """
- # Due to XPU doesn't support tuning yet
- device = "cpu" if device == "xpu" else device
- if model.device.type == "meta":
- model = model.to(device)
- if inplace:
- compressed_model = model
- else:
- compressed_model = copy.deepcopy(model)
- if isinstance(layer_config, str):
- with open(layer_config, "r") as f:
- q_config = json.load(f)
- else:
- q_config = layer_config
-
- for k, v in q_config.items():
- if check_to_quantized(v) is False:
- continue
- logger.info(f"Packing {k}")
- dtype = v["data_type"]
- bits = v["bits"]
- group_size = v["group_size"]
- sym = v["sym"]
- scale_dtype = v["scale_dtype"]
- m = get_module(compressed_model, k)
- fp_weight = m.weight.data
- scale, zp = m.scale, m.zp
- if isinstance(zp, int | float):
- zp = torch.full_like(scale, zp)
- convert_dtype = scale_dtype
- if not isinstance(scale, torch.Tensor):
- scale = torch.tensor(scale, dtype=convert_dtype)
- zp = torch.tensor(zp, dtype=torch.int32)
- else:
- if not inplace:
- scale = scale.clone()
- zp = zp.clone() if isinstance(zp, torch.Tensor) else zp
- else:
- scale = scale.to(dtype=convert_dtype)
- zp = zp.to(dtype=torch.int32) if isinstance(zp, torch.Tensor) else zp
- if type(m) == transformers.pytorch_utils.Conv1D:
- fp_weight = fp_weight.t_().contiguous()
- int_weight = quant_weight_w_scale(fp_weight, scale, zp, group_size, fp_weight.device)
- if type(m) == torch.nn.Linear:
- in_features = m.in_features
- out_features = m.out_features
- elif type(m) == transformers.pytorch_utils.Conv1D:
- in_features = m.weight.shape[0]
- out_features = m.weight.shape[1]
- int_weight = int_weight.type(torch.int32)
- new_module = WeightOnlyLinear(
- in_features,
- out_features,
- bits,
- group_size,
- dtype=dtype,
- scale_dtype=scale_dtype,
- zp=zp is not None,
- bias=m.bias is not None,
- device=device,
- compression_dtype=compression_dtype,
- compression_dim=compression_dim,
- use_optimum_format=use_optimum_format, # xpu is False
- )
- new_module.pack(int_weight, scale, zp, m.bias)
- set_module(compressed_model, k, new_module)
- return compressed_model
diff --git a/auto_round/export/export_to_itrex/model_wrapper.py b/auto_round/export/export_to_itrex/model_wrapper.py
deleted file mode 100644
index d6120cd72..000000000
--- a/auto_round/export/export_to_itrex/model_wrapper.py
+++ /dev/null
@@ -1,527 +0,0 @@
-#
-# -*- coding: utf-8 -*-
-#
-# Copyright (c) 2021 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.
-"""Torch.nn.Module Class Definition."""
-# Note: Do not import this file unless you have already imported torch,
-# since the model classes inherit torch.nn.Module.
-import math
-
-import numpy as np
-import torch
-from packaging.version import Version
-from torch.autograd import Function
-from torch.nn import functional as F
-
-from auto_round.utils import can_pack_with_numba, logger
-
-NF4 = [
- -1.0,
- -0.6961928009986877,
- -0.5250730514526367,
- -0.39491748809814453,
- -0.28444138169288635,
- -0.18477343022823334,
- -0.09105003625154495,
- 0.0,
- 0.07958029955625534,
- 0.16093020141124725,
- 0.24611230194568634,
- 0.33791524171829224,
- 0.44070982933044434,
- 0.5626170039176941,
- 0.7229568362236023,
- 1.0,
-]
-FP4_BNB = [-12.0, -8.0, -6.0, -4.0, -3.0, -2.0, -0.0625, 0, 0.0625, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0]
-FP4_E2M1 = [-6.0, -4.0, -3.0, -2.0, -1.5, -1.0, -0.0625, 0, 0.0625, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0]
-
-# the order is the same as float list, bit value range is [-7, 7]
-# 1111 = -1, 1110 = -2, 1101= -3, ...
-
-NF4_BIT = [7, 1, 2, 3, 4, 5, 6, 0, -8, -7, -6, -5, -4, -3, -2, -1]
-FP4_BNB_BIT = [-5, -6, -3, -4, -1, -2, -7, 0, 1, 6, 7, 4, 5, 2, 3]
-FP4_E2M1_BIT = [-1, -2, -3, -4, -5, -6, -7, 0, 1, 2, 3, 4, 5, 6, 7]
-
-FLOAT_MAPPING = {
- "nf4": NF4,
- "fp4": FP4_BNB,
- "fp4_e2m1_bnb": FP4_BNB,
- "fp4_e2m1": FP4_E2M1,
-}
-INT_MAPPING = {
- "nf4": NF4_BIT,
- "fp4": FP4_BNB_BIT,
- "fp4_e2m1_bnb": FP4_BNB_BIT,
- "fp4_e2m1": FP4_E2M1_BIT,
-}
-
-
-def get_torch_version():
- try:
- torch_version = torch.__version__.split("+")[0]
- except ValueError as e: # pragma: no cover
- assert False, "Got an unknown version of torch: {}".format(e)
- version = Version(torch_version)
- return version
-
-
-PT_VERSION = get_torch_version().release
-
-
-class WeightOnlyLinear(torch.nn.Module):
-
- def __init__(
- self,
- in_features,
- out_features,
- bits,
- groupsize,
- dtype="int",
- zp=False,
- bias=False,
- scale_dtype=torch.float16,
- compression_dtype=torch.int32,
- compression_dim=1,
- device="cpu",
- use_optimum_format=True,
- use_legacy_pack=False,
- ):
- super().__init__()
- self.use_optimum_format = use_optimum_format
- self.dtype = dtype
- if "int" not in self.dtype: # for nf4, fp4
-
- float_list = FLOAT_MAPPING[self.dtype]
- int_list = INT_MAPPING[self.dtype]
- self.int2float_mapping = {}
- for k, v in zip(int_list, float_list):
- self.int2float_mapping[k] = v
- self.device = device
- self.in_features = in_features
- self.out_features = out_features
- self.bits = bits
- self.groupsize = groupsize if groupsize != -1 else in_features
- self.compression_dim = compression_dim
- assert compression_dtype in [
- torch.int8,
- torch.int16,
- torch.int32,
- torch.int64,
- ], "Only support torch.int8|16|32|64 as compressed dtype."
- dtype_bits_mapping = {torch.int8: 8, torch.int16: 16, torch.int32: 32, torch.int64: 64}
- self.compress_bits = dtype_bits_mapping[compression_dtype]
- self.n_pack = self.compress_bits // self.bits
- # K is input channel, N is output channel
- assert compression_dim in [0, 1], (
- "Only support 0 or 1 as compression dimension, " + "0 is output channel, 1 is input channel."
- )
- if self.use_optimum_format:
- self.float_type = scale_dtype
- self.compression_dtype = torch.int32
- self.register_buffer(
- "scales",
- torch.zeros(
- (math.ceil(in_features / self.groupsize), out_features),
- dtype=self.float_type,
- ).to(device),
- )
- self.register_buffer(
- "qweight",
- torch.zeros(
- (math.ceil(in_features / self.n_pack), out_features),
- dtype=self.compression_dtype,
- ).to(device),
- )
- self.register_buffer(
- "qzeros",
- torch.zeros(
- (math.ceil(self.in_features / self.groupsize), math.ceil(self.out_features / self.n_pack)),
- dtype=self.compression_dtype,
- ).to(device),
- )
- self.register_buffer("bias", torch.zeros(self.out_features, dtype=self.float_type).to(device))
- else:
- self.compression_dtype = compression_dtype
- self.float_type = scale_dtype
- self.register_buffer(
- "scales",
- torch.zeros(
- (out_features, math.ceil(in_features / self.groupsize)),
- dtype=self.float_type,
- ).to(device),
- )
- if compression_dim == 1:
- self.register_buffer(
- "qweight",
- torch.zeros(
- (out_features, math.ceil(in_features / self.n_pack)),
- dtype=self.compression_dtype,
- ).to(device),
- )
- if zp:
- self.register_buffer(
- "qzeros",
- torch.zeros(
- (self.out_features, math.ceil(self.in_features / self.groupsize / self.n_pack)),
- dtype=self.compression_dtype,
- ).to(device),
- )
- else:
- self.register_buffer(
- "qweight",
- torch.zeros(
- (math.ceil(out_features / self.n_pack), in_features),
- dtype=self.compression_dtype,
- ).to(device),
- )
- if zp:
- self.register_buffer(
- "qzeros",
- torch.zeros(
- (math.ceil(self.out_features / self.n_pack), math.ceil(self.in_features / self.groupsize)),
- dtype=self.compression_dtype,
- ).to(device),
- )
- if bias:
- self.register_buffer("bias", torch.zeros(self.out_features, dtype=self.float_type).to(device))
- else:
- self.bias = None
- self.pack_func = self.pack_tensor_native_impl if use_legacy_pack else self.pack_tensor
-
- def pack_tensor_native_impl(self, raw_tensor):
- mask = torch.tensor(2**self.bits - 1, dtype=self.compression_dtype).to(self.device)
- target_len = math.ceil(raw_tensor.shape[1] / self.n_pack)
- packed_tensor = torch.zeros(raw_tensor.shape[0], target_len, dtype=self.compression_dtype).to(raw_tensor.device)
- for j in range(packed_tensor.shape[1]):
- start = self.n_pack * j
- end = self.n_pack * (j + 1)
- tmp = raw_tensor[:, start:end].type(self.compression_dtype)
- for e in range(tmp.shape[1]):
- tmp[:, e] &= mask
- tmp[:, e] = tmp[:, e] << (self.bits * e)
- packed_tensor[:, j] |= tmp[:, e]
- return packed_tensor
-
- def pack(self, int_weight, scale, zp, bias):
- if self.use_optimum_format:
- self.scales = self.scales.t_().contiguous()
- self.qweight = self.qweight.t_().contiguous()
- self.qzeros = self.qzeros.t_().contiguous()
-
- int_weight = int_weight.to(self.device)
- if self.use_optimum_format and zp is None:
- # to avoid overflow
- int_weight = int_weight.type(torch.int32)
- shift_bias = 2 ** (self.bits - 1)
- int_weight += shift_bias
- zp = torch.zeros_like(scale, dtype=torch.uint8) + shift_bias
- if bias is not None:
- assert hasattr(self, "bias"), "bias is not set when initializing."
- self.bias = bias.type(self.float_type).to(self.device)
- assert (
- scale.shape == self.scales.shape
- ), f"Scale shape is mismatched, expect {self.scales.shape}, got {scale.shape}"
- self.scales = scale.type(self.float_type).to(self.device)
- if not self.use_optimum_format and self.compression_dim == 0:
- int_weight = int_weight.t_().contiguous()
- self.qweight = self.qweight.t_().contiguous()
- origin_shape = int_weight.shape
- target_shape = self.qweight.shape
- assert origin_shape[0] == target_shape[0], "output channels mismatch, please check."
-
- # pack weight
- self.qweight.copy_(self.pack_func(int_weight))
- if not self.use_optimum_format and self.compression_dim == 0:
- self.qweight = self.qweight.t_().contiguous()
-
- if zp is not None:
- zp = zp.to(self.device) if isinstance(zp, torch.Tensor) else zp
- if self.use_optimum_format:
- zp -= 1
- if self.use_optimum_format or self.compression_dim == 0:
- zp = zp.t_().contiguous()
- self.qzeros = self.qzeros.t_().contiguous()
- assert hasattr(self, "qzeros"), "zp is not set when initializing."
- self.qzeros.copy_(self.pack_func(zp))
- if self.use_optimum_format or self.compression_dim == 0:
- self.qzeros = self.qzeros.t_().contiguous()
- if self.use_optimum_format:
- self.scales = self.scales.t_().contiguous()
- self.qweight = self.qweight.t_().contiguous()
- self.qzeros = self.qzeros.t_().contiguous()
-
- def recover(self):
- logger.debug(f"Recovering {self} weight")
- scales = self.scales.t_().contiguous() if self.use_optimum_format else self.scales
- qweight = self.qweight.t_().contiguous() if self.use_optimum_format else self.qweight
-
- device = scales.device
- fp32_weight = torch.zeros(self.out_features, self.in_features, dtype=self.float_type).to(device)
- mask = torch.tensor(2**self.bits - 1, dtype=self.compression_dtype).to(device)
- if hasattr(self, "qzeros"):
- weight_dtype = torch.uint8
- else:
- weight_dtype = torch.int8
- # unpack weight
- weight = torch.zeros(self.out_features, self.in_features, dtype=weight_dtype).to(device)
- if not self.use_optimum_format and self.compression_dim == 0:
- weight = weight.t_().contiguous()
- qweight = qweight.t_().contiguous()
- origin_shape = weight.shape
- target_shape = qweight.shape
- for j in range(target_shape[1]):
- for e in range(self.n_pack):
- index = j * self.n_pack + e
- if index >= origin_shape[1]:
- continue
- tmp = qweight[:, j]
- tmp = tmp << (self.compress_bits - self.bits * (e + 1))
- tmp = tmp >> self.compress_bits - self.bits
- if weight_dtype == torch.uint8:
- tmp &= mask # remove sign bit
- weight[:, index] = tmp.type(weight_dtype)
- if not self.use_optimum_format and self.compression_dim == 0:
- weight = weight.t_().contiguous()
- if "int" not in self.dtype:
- new_weight = torch.zeros(self.out_features, self.in_features).to(device)
- for k, v in self.int2float_mapping.items():
- new_weight += torch.where(weight == k, v, 0)
- weight = new_weight
- # unpack zero_point
- if hasattr(self, "qzeros"):
- zp_dtype = self.compression_dtype # to avoid overflow when weight-zp
- zp = torch.zeros(scales.shape, dtype=zp_dtype).to(device)
- qzeros = self.qzeros.t_().contiguous() if self.use_optimum_format else self.qzeros
- if self.use_optimum_format or self.compression_dim == 0:
- zp = zp.t_().contiguous()
- qzeros = qzeros.t_().contiguous()
- origin_shape = zp.shape
- target_shape = qzeros.shape
- for j in range(target_shape[1]):
- for e in range(self.n_pack):
- index = j * self.n_pack + e
- if index >= origin_shape[1]:
- continue
- tmp = qzeros[:, j]
- tmp = tmp << (self.compress_bits - self.bits * (e + 1))
- tmp = tmp >> self.compress_bits - self.bits
- tmp &= mask
- zp[:, index] = tmp.type(zp_dtype)
- if self.use_optimum_format or self.compression_dim == 0:
- zp = zp.t_().contiguous()
- if self.use_optimum_format:
- # zp -= 1 may cause zp == -1, after recover it becomes 2**self.bits - 1
- zp += 1
- zp = torch.where(zp > (2**self.bits - 1), 0, zp)
- # recover fp32 weight with int_weight, scale, and zero_point
- for idx in range(self.in_features):
- g_idx = idx // self.groupsize
- fp32_weight[:, idx] = (weight[:, idx] - zp[:, g_idx]) * scales[:, g_idx]
- else:
- # recover fp32 weight with int_weight, scale
- for idx in range(self.in_features):
- g_idx = idx // self.groupsize
- fp32_weight[:, idx] = weight[:, idx] * scales[:, g_idx]
- return fp32_weight
-
- def forward(self, input):
- if not hasattr(self, "weight"):
- weight = self.recover()
- device = self.scales.device
- if weight.dtype == torch.float16 and device.type == "cpu":
- weight = weight.float()
- self.bias = self.bias.float() if self.bias is not None else None
- if True: # keep reusing self.weight due to recover is too slow.
- if not hasattr(self, "weight"):
- self.weight = weight
- input = input.type(self.weight.dtype)
- logger.debug(f"Calculating {self}")
- return F.linear(input, self.weight, self.bias) # pylint: disable=E1102
- else:
- input = input.type(weight.dtype)
- return F.linear(input, weight, self.bias) # pylint: disable=E1102
-
- def extra_repr(self) -> str:
- tmp_str = "in_features={}, out_features={}, bits={}, group_size={}, bias={}".format(
- self.in_features,
- self.out_features,
- self.bits,
- self.groupsize,
- self.bias is not None,
- )
- if self.use_optimum_format:
- tmp_str += ", use_optimum_format=True"
- return tmp_str
-
- def pack_tensor_with_torch(self, raw_tensor):
- """Pack the tensor with torch.
-
- Args:
- raw_tensor (tensor): raw tensor.
-
- Returns:
- tensor: packed tensor.
- """
- target_len = math.ceil(raw_tensor.shape[1] / self.n_pack)
- packed_tensor = torch.zeros(raw_tensor.shape[0], target_len, dtype=self.compression_dtype).to(raw_tensor.device)
- mask = torch.tensor(2**self.bits - 1, dtype=self.compression_dtype).to(raw_tensor.device)
- for j in range(packed_tensor.shape[1]):
- start = self.n_pack * j
- end = self.n_pack * (j + 1)
- tmp = raw_tensor[:, start:end].type(self.compression_dtype)
- tmp &= mask
- for e in range(tmp.shape[1]):
- tmp[:, e] = tmp[:, e] << (self.bits * e)
- packed_tensor[:, j] |= tmp[:, e]
- return packed_tensor
-
- def unpack_tensor_with_torch(self, packed_tensor):
- """Unpack the tensor with torch.
-
- Args:
- packed_tensor (tensor): packed tensor.
-
- Returns:
- tensor: unpacked tensor.
- """
- target_dtype = torch.int16
- target_len = packed_tensor.shape[1] * self.n_pack
- unpacked_tensor = torch.zeros(packed_tensor.shape[0], target_len, dtype=target_dtype).to(packed_tensor.device)
- mask = torch.tensor(2**self.bits - 1, dtype=self.compression_dtype).to(packed_tensor.device)
- for j in range(packed_tensor.shape[1]):
- for e in range(self.n_pack):
- index = j * self.n_pack + e
- tmp = packed_tensor[:, j]
- tmp = tmp << (self.compress_bits - self.bits * (e + 1))
- tmp = tmp >> self.compress_bits - self.bits
- if hasattr(self, "qzeros"):
- tmp &= mask # remove sign bit
- unpacked_tensor[:, index].copy_(tmp.type(target_dtype))
- return unpacked_tensor
-
- def pack_array_with_numba(
- self,
- raw_array: np.ndarray,
- n_pack: int,
- bits: int,
- compress_bits: int,
- compression_dtype=np.int32,
- ) -> np.ndarray:
- """Packs the input array by combining elements into a specified bit-width format using NumPy.
-
- Args:
- raw_array (np.ndarray): The array to be packed. Shape: [out_features, in_features] or [1, in_features].
- n_pack (int): The number of elements to be packed together.
- bits (int): The number of bits for each element.
- compress_bits (int): The number of bits for each element of the compressed array, supported 2, 4, 8.
- compression_dtype (np.dtype, optional): The data type of the compressed array. Defaults to np.int32.
-
- Returns:
- np.ndarray: The packed array.
- """
- # Try to pack with numba to accelerate the packing process.
- # If numba is not availabll or the packing method is not supported,
- # fallback to the torch implementation.
- if not can_pack_with_numba():
- return self.pack_tensor_with_torch(torch.from_numpy(raw_array)).cpu().numpy()
-
- from auto_round.export.export_to_itrex.bit_packer import bit_packers
-
- pack_func_name = (bits, compress_bits)
- if pack_func_name not in bit_packers:
- logger.warning(
- (
- f"Unsupported packing with bits: {bits}, compress_bits: {compress_bits} using numba, "
- "fallback to torch implementation."
- )
- )
- return self.pack_tensor_with_torch(torch.from_numpy(raw_array)).cpu().numpy()
- out_features, in_features = raw_array.shape
- new_in_features = (in_features + n_pack - 1) // n_pack
- packed_array = np.zeros((out_features, new_in_features), dtype=compression_dtype)
- raw_array = raw_array.astype(compression_dtype)
- pack_method = bit_packers[pack_func_name]
- return pack_method(raw_array, packed_array, n_pack, new_in_features)
-
- def pack_tensor_with_numpy_impl(self, raw_tensor):
- """The implement of packing tensor with numpy."""
- raw_array = raw_tensor.cpu().numpy()
- target_len = np.ceil(raw_array.shape[1] / self.n_pack).astype(int)
- target_dtype = torch.tensor(0, dtype=self.compression_dtype).numpy().dtype
- packed_array = np.zeros((raw_array.shape[0], target_len), dtype=target_dtype)
- mask = np.uint8(2**self.bits - 1)
- for j in range(packed_array.shape[1]):
- start = self.n_pack * j
- end = self.n_pack * (j + 1)
- tmp = raw_array[:, start:end].astype(target_dtype)
- tmp &= mask
- for e in range(tmp.shape[1]):
- tmp[:, e] = np.left_shift(tmp[:, e], self.bits * e)
- packed_array[:, j] |= tmp[:, e]
- packed_tensor = torch.from_numpy(packed_array).to(device=raw_tensor.device)
- return packed_tensor
-
- def pack_tensor_with_numpy(self, raw_tensor):
- """Pack the tensor with numpy."""
- if self.bits == 8 and self.compression_dtype == torch.int8:
- return raw_tensor
- if self.bits not in [2, 4, 8]:
- return self.pack_tensor_with_numpy_impl(raw_tensor)
- compression_dtype = torch.tensor(0, dtype=self.compression_dtype).numpy().dtype
- packed_array = self.pack_array_with_numba(
- raw_tensor.cpu().numpy(),
- self.n_pack,
- self.bits,
- self.compress_bits,
- compression_dtype,
- )
- return torch.from_numpy(packed_array).to(device=raw_tensor.device)
-
- def unpack_tensor_with_numpy(self, packed_tensor):
- """Unpack the packed tensor with numpy."""
- packed_array = packed_tensor.cpu().numpy()
- target_dtype = np.int16
- if self.bits == 8 and self.compression_dtype == torch.int8 and hasattr(self, "qzeros"):
- # special case for unpacking uint8 date from int8 compression_dtype
- target_dtype = np.uint8
- target_len = packed_array.shape[1] * self.n_pack
- unpacked_array = np.zeros((packed_array.shape[0], target_len), dtype=target_dtype)
- mask = np.uint8(2**self.bits - 1)
- for j in range(packed_array.shape[1]):
- for e in range(self.n_pack):
- index = j * self.n_pack + e
- tmp = packed_array[:, j]
- tmp = np.left_shift(tmp, self.compress_bits - self.bits * (e + 1))
- tmp = np.right_shift(tmp, self.compress_bits - self.bits)
- if hasattr(self, "qzeros"):
- tmp &= mask
- unpacked_array[:, index] = tmp.astype(target_dtype)
- unpacked_tensor = torch.from_numpy(unpacked_array).to(device=packed_tensor.device)
- return unpacked_tensor
-
- def pack_tensor(self, raw_tensor):
- """Pack tensor."""
- if "cuda" in raw_tensor.device.type:
- return self.pack_tensor_with_torch(raw_tensor)
- else:
- return self.pack_tensor_with_numpy(raw_tensor)
-
- def unpack_tensor(self, packed_tensor):
- """Unpack tensor."""
- if "cuda" in packed_tensor.device.type:
- return self.unpack_tensor_with_torch(packed_tensor)
- else:
- return self.unpack_tensor_with_numpy(packed_tensor)
diff --git a/auto_round/formats.py b/auto_round/formats.py
index b853dae22..6ec6e9b15 100644
--- a/auto_round/formats.py
+++ b/auto_round/formats.py
@@ -591,48 +591,6 @@ class AutoAWQFormat(OutputFormat):
)
[email protected]("itrex_xpu")
-class ITREXFormat(OutputFormat):
- support_schemes = ["W4A16", "W2A16", "W3A16", "W8A16", "BF16", "W2A16G64", "W2A16G32"]
- format_name = "itrex"
-
- def pack_layer(self, *args, **kwargs):
- pass
-
- def save_quantized(
- self,
- output_dir: str,
- model: torch.nn.Module = None,
- tokenizer: Callable = None,
- layer_config: dict = None,
- inplace: bool = True,
- device: Union[str, torch.device] = "cpu",
- serialization_dict: dict = None,
- **kwargs,
- ) -> torch.nn.Module:
- backend = self.get_backend_name()
- if backend == "itrex":
- from auto_round.export.export_to_itrex.export import save_quantized_as_itrex
-
- export_func = save_quantized_as_itrex
- else:
- from auto_round.export.export_to_itrex.export import save_quantized_as_itrex_xpu
-
- export_func = save_quantized_as_itrex_xpu
- return export_func(
- output_dir=output_dir,
- model=model,
- tokenizer=tokenizer,
- layer_config=layer_config,
- inplace=inplace,
- device=device,
- backend=backend,
- serialization_dict=serialization_dict,
- **kwargs,
- )
-
-
@OutputFormat.register("gguf")
class GGUFFormat(OutputFormat):
support_schemes = [
diff --git a/auto_round/inference/convert_model.py b/auto_round/inference/convert_model.py
index fc5d5e7ba..1041d2a49 100644
--- a/auto_round/inference/convert_model.py
+++ b/auto_round/inference/convert_model.py
@@ -472,7 +472,7 @@ def post_init(model: torch.nn.Module, used_backends: list[str]) -> None:
"""Performs post-initialization for different quantization backends.
This function handles backend-specific post-init steps, including AutoGPTQ,
- GPTQModel, IPEX/ITREx layers, and ExLLaMAv2 kernels. It also ensures the
+ GPTQModel, IPEX layers, and ExLLaMAv2 kernels. It also ensures the
model's data type is compatible with all used backends.
Args:
@@ -482,7 +482,7 @@ def post_init(model: torch.nn.Module, used_backends: list[str]) -> None:
"""
need_autogptq_init = False
need_gptqmodel_init = False
- need_ipex_itrex_init = False
+ need_ipex_init = False
used_gptq_exllamav2 = False
# Determine which backends require post-init
for backend in used_backends:
@@ -493,7 +493,7 @@ def post_init(model: torch.nn.Module, used_backends: list[str]) -> None:
elif backend.startswith("gptqmodel"):
need_gptqmodel_init = True
elif backend.startswith(("ipex", "auto_round_kernel")):
- need_ipex_itrex_init = True
+ need_ipex_init = True
# AutoGPTQ post-init
if need_autogptq_init:
@@ -507,8 +507,8 @@ def post_init(model: torch.nn.Module, used_backends: list[str]) -> None:
model = gptq_post_init(model, use_act_order=False)
- # IPEX/ITREx post-init
- if need_ipex_itrex_init:
+ # IPEX post-init
+ if need_ipex_init:
message = "repacking to CPU/XPU format"
layers = [] ## ipex post_init will add one more layer
for n, m in model.named_modules():
diff --git a/auto_round/testing_utils.py b/auto_round/testing_utils.py
index d67329c2d..d9685e604 100644
--- a/auto_round/testing_utils.py
+++ b/auto_round/testing_utils.py
@@ -47,10 +47,6 @@ def is_ipex_available():
return False
-def is_itrex_available():
- return importlib.util.find_spec("intel_extension_for_transformers") is not None
-
-
def is_flash_attn_available():
return importlib.util.find_spec("flash_attn") is not None
@@ -129,16 +125,6 @@ def require_ipex(test_case):
return unittest.skipUnless(is_ipex_available(), "test requires intel-extension-for-pytorch>=2.5")(test_case)
-def require_itrex(test_case):
- """
- Decorator marking a test that requires intel-extension-for-transformers.
-
- These tests are skipped when intel-extension-for-transformers isn't installed.
-
- """
- return unittest.skipUnless(is_itrex_available(), "test requires intel-extension-for-transformers")(test_case)
-
-
def require_optimum(test_case):
"""
Decorator marking a test that optimum.
diff --git a/docs/step_by_step.md b/docs/step_by_step.md
index 9c77d15d8..519d82d2f 100644
--- a/docs/step_by_step.md
+++ b/docs/step_by_step.md
@@ -702,7 +702,6 @@ print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50, do_sample=Fal
| Name | Devices | Bits | Dtypes | Priority | Packing format | Requirements |
|--------------------------------------|----------|---------|-----------|----------|-----------------|-------------------------------|
| ipex | cpu/xpu | 4 | BF16/FP16 | 5 | gptq_zp+-1/awq | intel-extension-for-pytorch |
-| itrex | cpu | 2,4,8 | BF16/FP16 | 1 | gptq_zp+-1/awq | <br/>intel-extension-for-transformers |
| marlin | cuda | 4,8 | BF16/FP16 | 6 | gptq/gptq_zp+-1 | gptqmodel |
| exllamav2 or<br/>gptqmodel:exllamav2 | cuda | 4 | BF16/FP16 | 5 | gptq | gptqmodel |
| exllamav2 or<br/>gptq:exllamav2 | cuda | 4 | FP16 | 5 | gptq_zp+-1 | auto-gptq |
diff --git a/test/test_cpu/core/test_autoround_export_to_itrex.py b/test/test_cpu/core/test_autoround_export_to_itrex.py
deleted file mode 100644
index 08a4e7753..000000000
--- a/test/test_cpu/core/test_autoround_export_to_itrex.py
+++ /dev/null
@@ -1,101 +0,0 @@
-import copy
-import shutil
-
-import pytest
-import torch
-import transformers
-from transformers import AutoModelForCausalLM, AutoTokenizer
-
-from auto_round import AutoRound
-
-from ...helpers import get_model_path, gptj_name_or_path
-
-
-class SimpleDataLoader:
- def __init__(self):
- self.batch_size = 1
-
- def __iter__(self):
- for i in range(2):
- yield torch.randn([1, 30])
-
-
-class TestAutoroundExport:
- approach = "weight_only"
-
- @classmethod
- def setup_class(self):
- self.gptj = transformers.AutoModelForCausalLM.from_pretrained(
- gptj_name_or_path,
- torchscript=True,
- )
- self.tokenizer = transformers.AutoTokenizer.from_pretrained(gptj_name_or_path, trust_remote_code=True)
- self.gptj_no_jit = transformers.AutoModelForCausalLM.from_pretrained(
- gptj_name_or_path,
- )
- self.lm_input = torch.ones([1, 10], dtype=torch.long)
-
- @classmethod
- def teardown_class(self):
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- def test_autoround_int_quant(self):
- model = copy.deepcopy(self.gptj)
- out1 = model(self.lm_input)
- round = AutoRound
- optq_1 = round(model, self.tokenizer, nsamples=1, amp=False, seqlen=10, iters=10, enable_torch_compile=False)
- q_model, layer_config1 = optq_1.quantize() ##compile model
- from auto_round.export.export_to_itrex import pack_model
-
- compressed_model = pack_model(model=q_model, layer_config=layer_config1)
- out2 = model(self.lm_input)
- out3 = q_model(self.lm_input)
- out4 = compressed_model(self.lm_input)
- assert torch.all(torch.isclose(out1[0], out2[0], atol=1e-1))
- assert not torch.all(out1[0] == out2[0])
- assert torch.all(out2[0] == out3[0])
- assert torch.all(torch.isclose(out3[0], out4[0], atol=1e-3))
- assert "transformer.h.0.attn.k_proj.qzeros" in compressed_model.state_dict().keys()
-
- model = copy.deepcopy(self.gptj)
- out6 = model(self.lm_input)
- optq_2 = round(model, self.tokenizer, device="cpu", nsamples=1, seqlen=10)
- q_model, layer_config2 = optq_2.quantize()
- compressed_model = pack_model(model=q_model, layer_config=layer_config2, inplace=False)
- compressed_model = compressed_model.to(torch.float32)
- out4 = q_model(self.lm_input)
- out5 = compressed_model(self.lm_input)
- assert torch.all(out1[0] == out6[0])
- assert torch.all(torch.isclose(out4[0], out5[0], atol=5e-3))
-
- def test_config(self):
- from auto_round.export.export_to_itrex import QuantConfig
-
- config = QuantConfig.from_pretrained(get_model_path("TheBloke/Llama-2-7B-Chat-GPTQ"))
- config.save_pretrained("quantization_config_dir")
- loaded_config = QuantConfig.from_pretrained("quantization_config_dir")
- assert config.group_size == loaded_config.group_size
- assert config.desc_act == loaded_config.desc_act
- assert config.bits == loaded_config.bits
- assert config.sym == loaded_config.sym
-
- def test_xpu_export(self):
- model = copy.deepcopy(self.gptj)
- out1 = model(self.lm_input)
- round = AutoRound
- optq_1 = round(model, self.tokenizer, nsamples=1, amp=False, seqlen=10, iters=10, enable_torch_compile=False)
- q_model, layer_config1 = optq_1.quantize()
- from auto_round.export.export_to_itrex import pack_model
-
- compressed_model_xpu = pack_model(model=q_model, layer_config=layer_config1, device="xpu", inplace=False)
- compressed_model_cpu = pack_model(model=q_model, layer_config=layer_config1, inplace=False)
- out2 = model(self.lm_input)
- out3 = q_model(self.lm_input)
- out4 = compressed_model_xpu(self.lm_input)
- out5 = compressed_model_cpu(self.lm_input)
- assert torch.all(torch.isclose(out1[0], out2[0], atol=1e-1))
- assert not torch.all(out1[0] == out2[0])
- assert torch.all(out2[0] == out3[0])
- assert torch.all(torch.isclose(out3[0], out4[0], atol=1e-3))
- assert torch.all(torch.isclose(out4[0], out5[0], atol=1e-5))
diff --git a/test/test_cpu/utils/test_woq_linear.py b/test/test_cpu/utils/test_woq_linear.py
deleted file mode 100644
index 8f5bedc2c..000000000
--- a/test/test_cpu/utils/test_woq_linear.py
+++ /dev/null
@@ -1,77 +0,0 @@
-import pytest
-import torch
-
-from auto_round.export.export_to_itrex.model_wrapper import WeightOnlyLinear
-
-
-class TestWeightOnlyLinear:
- @pytest.mark.parametrize(
- "bits, compression_dtype",
- [
- (8, torch.int16),
- (8, torch.int32),
- (8, torch.int64),
- (4, torch.int8),
- (4, torch.int16),
- (4, torch.int32),
- (4, torch.int64),
- (2, torch.int8),
- (2, torch.int16),
- (2, torch.int32),
- (2, torch.int64),
- ],
- )
- def test_pack_with_numba(self, bits, compression_dtype):
- m = torch.nn.Linear(1024, 512)
- dtype = "int"
- weight = m.weight.detach()
- group_size = 32
- origin_shape = weight.shape
- from auto_round.data_type.int import quant_tensor_sym
-
- origin_shape = weight.shape
- weight = weight.reshape(-1, group_size)
- qdq, scale, zp = quant_tensor_sym(weight, -1)
- if isinstance(zp, int | float):
- zp = torch.full_like(scale, zp)
- int_weight = qdq.div(scale).add(zp).clamp(0, 2 ** (bits) - 1).to(torch.int32).reshape(origin_shape)
- scale = scale.reshape(origin_shape[0], -1)
- if isinstance(zp, torch.Tensor):
- zp = zp.reshape(origin_shape[0], -1).to(torch.int32).clamp(0, 2 ** (bits) - 1)
- module_with_legacy_pack = WeightOnlyLinear(
- in_features=m.in_features,
- out_features=m.out_features,
- dtype=dtype,
- bits=bits,
- groupsize=32,
- zp=zp is not None,
- bias=m.bias is not None,
- use_optimum_format=False,
- compression_dtype=compression_dtype,
- use_legacy_pack=True,
- )
- module_with_legacy_pack.pack(
- int_weight.clone(), scale.clone(), zp.clone() if isinstance(zp, torch.Tensor) else zp, m.bias
- )
- module_with_new_pack = WeightOnlyLinear(
- in_features=m.in_features,
- out_features=m.out_features,
- dtype=dtype,
- bits=bits,
- groupsize=32,
- zp=zp is not None,
- bias=m.bias is not None,
- use_optimum_format=False,
- compression_dtype=compression_dtype,
- use_legacy_pack=False,
- )
- module_with_new_pack.pack(
- int_weight.clone(), scale.clone(), zp.clone() if isinstance(zp, torch.Tensor) else zp, m.bias
- )
-
- assert torch.equal(module_with_new_pack.qweight, module_with_legacy_pack.qweight)
-
- assert torch.equal(module_with_new_pack.qzeros, module_with_legacy_pack.qzeros)
- assert torch.equal(module_with_new_pack.scales, module_with_legacy_pack.scales)
- unpacked_int_weight = module_with_new_pack.unpack_tensor(module_with_legacy_pack.qweight)
- assert torch.equal(unpacked_int_weight, int_weight)
diff --git a/test/test_cuda/quantization/test_qbits.py b/test/test_cuda/quantization/test_qbits.py
deleted file mode 100644
index 6ebb9d67b..000000000
--- a/test/test_cuda/quantization/test_qbits.py
+++ /dev/null
@@ -1,112 +0,0 @@
-import shutil
-
-import pytest
-from transformers import AutoModelForCausalLM, AutoTokenizer
-
-from auto_round import AutoRound, AutoRoundConfig
-from auto_round.testing_utils import require_gptqmodel, require_itrex
-
-from ...helpers import get_model_path, model_infer
-
-
-class TestAutoRound:
- save_dir = "./saved"
-
- @pytest.fixture(autouse=True, scope="class")
- def setup_and_teardown_class(self):
- # ===== SETUP (setup_class) =====
- print("[Setup] Running before any test in class")
-
- # Yield to hand control to the test methods
- yield
-
- # ===== TEARDOWN (teardown_class) =====
- print("[Teardown] Running after all tests in class")
- shutil.rmtree("./saved", ignore_errors=True)
- shutil.rmtree("runs", ignore_errors=True)
-
- ## require torch 2.6
- @require_itrex
- def test_load_gptq_model_8bits(self):
- model_name = "acloudfan/opt-125m-gptq-8bit"
- quantization_config = AutoRoundConfig()
- model = AutoModelForCausalLM.from_pretrained(
- model_name,
- torch_dtype="auto",
- trust_remote_code=True,
- device_map="cpu",
- quantization_config=quantization_config,
- )
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
- model_infer(model, tokenizer)
-
- @require_itrex
- def test_load_gptq_model_2bits(self):
- model_name = "LucasSantiago257/gemma-2b-2bits-gptq"
- quantization_config = AutoRoundConfig()
- model = AutoModelForCausalLM.from_pretrained(
- model_name,
- torch_dtype="auto",
- trust_remote_code=True,
- device_map="cpu",
- quantization_config=quantization_config,
- )
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
- model_infer(model, tokenizer)
-
- @require_itrex
- def test_mixed_precision(self):
- model_path = get_model_path("facebook/opt-125m")
- model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype="auto", trust_remote_code=True)
- tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
- layer_config = {}
-
- layer_config["model.decoder.layers.0.self_attn.k_proj"] = {"bits": 8}
- layer_config["model.decoder.layers.6.self_attn.out_proj"] = {"bits": 2, "group_size": 32}
- bits, group_size, sym = 4, 128, True
- import torch
-
- from auto_round import AutoRound
-
- autoround = AutoRound(
- model, tokenizer, bits=bits, group_size=group_size, iters=1, nsamples=1, sym=sym, layer_config=layer_config
- )
- quantized_model_path = self.save_dir
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
-
- model = AutoModelForCausalLM.from_pretrained(
- self.save_dir,
- torch_dtype=torch.float16,
- device_map="cpu",
- )
- tokenizer = AutoTokenizer.from_pretrained(self.save_dir)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
- print(res)
- assert "!!!" not in res
- shutil.rmtree(self.save_dir, ignore_errors=True)
-
- @require_gptqmodel
- def test_autoround_sym(self, tiny_opt_model_path):
- for bits in [4]:
- model = AutoModelForCausalLM.from_pretrained(
- tiny_opt_model_path, torch_dtype="auto", trust_remote_code=True
- )
- tokenizer = AutoTokenizer.from_pretrained(tiny_opt_model_path, trust_remote_code=True)
- bits, group_size, sym = bits, 128, True
- autoround = AutoRound(model, tokenizer, bits=bits, group_size=group_size, sym=sym, iters=2, seqlen=2)
- quantized_model_path = "./saved"
-
- autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
-
- model = AutoModelForCausalLM.from_pretrained(
- quantized_model_path, device_map="auto", trust_remote_code=True
- )
- tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)
- text = "There is a girl who likes adventure,"
- inputs = tokenizer(text, return_tensors="pt").to(model.device)
- res = tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0])
- print(res)
- assert "!!!" not in res
- shutil.rmtree(self.save_dir, ignore_errors=True)
diff --git a/test/test_hpu/test_auto_round.py b/test/test_hpu/test_auto_round.py
index d2e33dd03..2ed43f846 100644
--- a/test/test_hpu/test_auto_round.py
+++ b/test/test_hpu/test_auto_round.py
@@ -42,11 +42,6 @@ def test_opt_125m_compile_mode():
run_opt_125m_on_hpu()
-def test_import():
- from auto_round import AutoRound
- from auto_round.export.export_to_itrex.export import WeightOnlyLinear, save_quantized_as_itrex
-
-
@pytest.mark.parametrize(
"data_type",
["fp8_to_int_sym"],