Skip to content

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

fix awq backend and fp_layers issue (#363)

Wenhua Cheng9b9eeb67fb25
diff --git a/README.md b/README.md
index a0e989fb5..8ee725206 100644
--- a/README.md
+++ b/README.md
@@ -345,48 +345,49 @@ Please note that an asterisk (*) indicates third-party quantized models, which m
different recipe. We greatly appreciate their efforts and encourage more users to share their models, as we cannot
release most of the models ourselves.
- Model | Supported |
-|----------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| Qwen/QwQ-32B-Preview | [model-opea-int4-sym-autoround-mixed](https://huggingface.co/OPEA/QwQ-32B-Preview-int4-sym-mixed-inc) |
-| THUDM/cogvlm2-llama3-chat-19B | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/cogvlm2-llama3-chat-19B-int4-sym-inc) |
-| Qwen/Qwen2-VL-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Qwen2-VL-7B-Instruct-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Qwen2-VL-7B-Instruct-int4-sym-inc) |
-| meta-llama/Llama-3.2-11B-Vision | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Llama-3.2-11B-Vision-Instruct-int4-sym-inc), [model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Llama-3.2-11B-Vision-Instruct-int4-sym-inc) |
-| microsoft/Phi-3.5-vision-instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Phi-3.5-vision-instruct-int4-sym-inc), [model-opea-int4-sym-gptq](https://huggingface.co/OPEA/Phi-3.5-vision-instruct-int4-sym-inc) |
-| liuhaotian/llava-v1.5-7b | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/llava-v1.5-7b-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/llava-v1.5-7b-int4-sym-inc) |
-| Qwen/Qwen2.5-7B-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Qwen2.5-7B-Instruct-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Qwen2.5-7B-Instruct-int4-sym-inc) [model-kaitchup-autogptq-int4*](https://beta-index.hf-mirror.com/kaitchup/Qwen2.5-7B-Instruct-AutoRound-GPTQ-asym-4bit), [recipe](./docs/Qwen2.5-7B-Instruct-sym.md) |
-| Qwen/Qwen2.5-14B-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Qwen2.5-14B-Instruct-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Qwen2.5-14B-Instruct-int4-sym-inc) |
-| Qwen/Qwen2.5-32B-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Qwen2.5-32B-Instruct-int4-sym-inc) |
-| Qwen/Qwen2.5-Coder-32B-Instruct | [model-kaitchup-autogptq-int4*](https://beta-index.hf-mirror.com/kaitchup/Qwen2.5-Coder-32B-Instruct-AutoRound-GPTQ-4bit) |
-| Qwen/Qwen2.5-72B-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Qwen2.5-72B-Instruct-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Qwen2.5-72B-Instruct-int4-sym-inc), [model-kaitchup-autogptq-int4*](https://beta-index.hf-mirror.com/kaitchup/Qwen2.5-72B-Instruct-AutoRound-GPTQ-4bit), [model-kaitchup-autogptq-int2*](https://beta-index.hf-mirror.com/kaitchup/Qwen2.5-72B-Instruct-AutoRound-GPTQ-2bit), [recipe](./docs/Qwen2.5-72B-Instruct-sym.md) |
-| meta-llama/Meta-Llama-3.1-70B-Instruct | [model-opea-int4-asym-autoround](https://huggingface.co/OPEA/Meta-Llama-3.1-70B-Instruct-int4-asym-incc) |
-| meta-llama/Meta-Llama-3.1-8B-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Meta-Llama-3.1-8B-Instruct-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Meta-Llama-3.1-8B-Instruct-int4-sym-inc),[model-kaitchup-autogptq-int4*](https://huggingface.co/kaitchup/Meta-Llama-3.1-8B-Instruct-autoround-gptq-4bit-asym), [model-kaitchup-autogptq-sym-int4*](https://huggingface.co/kaitchup/Meta-Llama-3.1-8B-Instruct-autoround-gptq-4bit-sym), [recipe](https://huggingface.co/Intel/Meta-Llama-3.1-8B-Instruct-int4-inc) |
-| meta-llama/Meta-Llama-3.1-8B | [model-kaitchup-autogptq-sym-int4*](https://huggingface.co/kaitchup/Meta-Llama-3.1-8B-autoround-gptq-4bit-sym) |
-| Qwen/Qwen-VL | [accuracy](./examples/multimodal-modeling/Qwen-VL/README.md), [recipe](./examples/multimodal-modeling/Qwen-VL/run_autoround.sh)
-| Qwen/Qwen2-7B | [model-autoround-sym-int4](https://huggingface.co/Intel/Qwen2-7B-int4-inc), [model-autogptq-sym-int4](https://huggingface.co/Intel/Qwen2-7B-int4-inc) |
-| THUDM/glm-4-9b-chat | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/glm-4-9b-chat-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/glm-4-9b-chat-int4-sym-inc) |
-| Qwen/Qwen2-57B-A14B-Instruct | [model-autoround-sym-int4](https://huggingface.co/Intel/Qwen2-57B-A14B-Instruct-int4-inc),[model-autogptq-sym-int4](https://huggingface.co/Intel/Qwen2-57B-A14B-Instruct-int4-inc) |
-| 01-ai/Yi-1.5-9B | [model-LnL-AI-autogptq-int4*](https://huggingface.co/LnL-AI/Yi-1.5-9B-4bit-gptq-autoround) |
-| 01-ai/Yi-1.5-9B-Chat | [model-LnL-AI-autogptq-int4*](https://huggingface.co/LnL-AI/Yi-1.5-9B-Chat-4bit-gptq-autoround) |
-| Intel/neural-chat-7b-v3-3 | [model-autogptq-int4](https://huggingface.co/Intel/neural-chat-7b-v3-3-int4-inc) |
-| Intel/neural-chat-7b-v3-1 | [model-autogptq-int4](https://huggingface.co/Intel/neural-chat-7b-v3-1-int4-inc) |
-| TinyLlama-1.1B-intermediate | [model-LnL-AI-autogptq-int4*](https://huggingface.co/LnL-AI/TinyLlama-1.1B-intermediate-step-1341k-3T-autoround-lm_head-symFalse) |
-| mistralai/Mistral-7B-v0.1 | [model-autogptq-lmhead-int4](https://huggingface.co/Intel/Mistral-7B-v0.1-int4-inc-lmhead), [model-autogptq-int4](https://huggingface.co/Intel/Mistral-7B-v0.1-int4-inc) |
-| google/gemma-2b | [model-autogptq-int4](https://huggingface.co/Intel/gemma-2b-int4-inc) |
-| tiiuae/falcon-7b | [model-autogptq-int4-G64](https://huggingface.co/Intel/falcon-7b-int4-inc) |
-| sapienzanlp/modello-italia-9b | [model-fbaldassarri-autogptq-int4*](https://huggingface.co/fbaldassarri/modello-italia-9b-autoround-w4g128-cpu) |
-| microsoft/phi-2 | [model-autoround-sym-int4](https://huggingface.co/Intel/phi-2-int4-inc) [model-autogptq-sym-int4](https://huggingface.co/Intel/phi-2-int4-inc) |
-| microsoft/Phi-3.5-mini-instruct | [model-kaitchup-autogptq-sym-int4*](https://huggingface.co/kaitchup/Phi-3.5-Mini-instruct-AutoRound-4bit) |
-| mistralai/Mistral-7B-Instruct-v0.2 | [outdated-recipe](./docs/Mistral-7B-Instruct-v0.2-asym-recipe.md) |
-| mistralai/Mixtral-8x7B-Instruct-v0.1 | [outdated-recipe](./docs/Mixtral-8x7B-Instruct-v0.1-asym-recipe.md) |
-| mistralai/Mixtral-8x7B-v0.1 | [outdated-recipe](./docs/Mixtral-8x7B-v0.1-asym-acc.md) |
-| meta-llama/Meta-Llama-3-8B-Instruct | [outdated-recipe](./docs/Meta-Llama-3-8B-Instruct-asym-recipe.md) |
-| google/gemma-7b | [outdated-recipe](./docs/gemma-7b-asym-recipe.md) |
-| meta-llama/Llama-2-7b-chat-hf | [outdated-recipe](./docs/Llama-2-7b-chat-hf-asym-recipe.md) |
-| baichuan-inc/Baichuan2-7B-Chat | [outdated-recipe](./docs/baichuan2-7b-cha-asym-recipe.md) |
-| 01-ai/Yi-6B-Chat | [outdated-recipe](./docs/Yi-6B-Chat-asym-recipe.md) |
-| facebook/opt-2.7b | [outdated-recipe](./docs/opt-2.7b-asym-recipe.md) |
-| bigscience/bloom-3b | [outdated-recipe](./docs/bloom-3B-asym-recipe.md) |
-| EleutherAI/gpt-j-6b | [outdated-recipe](./docs/gpt-j-6B-asym-recipe.md) |
+ Model | Supported |
+|------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| meta-llama/Llama-3.2-90B-Vision-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Llama-3.2-90B-Vision-Instruct-int4-sym-inc), [model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Llama-3.2-90B-Vision-Instruct-int4-sym-inc) |
+| Qwen/QwQ-32B-Preview | [model-opea-int4-sym-autoround-mixed](https://huggingface.co/OPEA/QwQ-32B-Preview-int4-sym-mixed-inc) |
+| THUDM/cogvlm2-llama3-chat-19B | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/cogvlm2-llama3-chat-19B-int4-sym-inc) |
+| Qwen/Qwen2-VL-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Qwen2-VL-7B-Instruct-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Qwen2-VL-7B-Instruct-int4-sym-inc) |
+| meta-llama/Llama-3.2-11B-Vision | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Llama-3.2-11B-Vision-Instruct-int4-sym-inc), [model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Llama-3.2-11B-Vision-Instruct-int4-sym-inc) |
+| microsoft/Phi-3.5-vision-instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Phi-3.5-vision-instruct-int4-sym-inc), [model-opea-int4-sym-gptq](https://huggingface.co/OPEA/Phi-3.5-vision-instruct-int4-sym-inc) |
+| liuhaotian/llava-v1.5-7b | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/llava-v1.5-7b-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/llava-v1.5-7b-int4-sym-inc) |
+| Qwen/Qwen2.5-7B-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Qwen2.5-7B-Instruct-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Qwen2.5-7B-Instruct-int4-sym-inc) [model-kaitchup-autogptq-int4*](https://beta-index.hf-mirror.com/kaitchup/Qwen2.5-7B-Instruct-AutoRound-GPTQ-asym-4bit), [recipe](./docs/Qwen2.5-7B-Instruct-sym.md) |
+| Qwen/Qwen2.5-14B-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Qwen2.5-14B-Instruct-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Qwen2.5-14B-Instruct-int4-sym-inc) |
+| Qwen/Qwen2.5-32B-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Qwen2.5-32B-Instruct-int4-sym-inc) |
+| Qwen/Qwen2.5-Coder-32B-Instruct | [model-kaitchup-autogptq-int4*](https://beta-index.hf-mirror.com/kaitchup/Qwen2.5-Coder-32B-Instruct-AutoRound-GPTQ-4bit) |
+| Qwen/Qwen2.5-72B-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Qwen2.5-72B-Instruct-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Qwen2.5-72B-Instruct-int4-sym-inc), [model-kaitchup-autogptq-int4*](https://beta-index.hf-mirror.com/kaitchup/Qwen2.5-72B-Instruct-AutoRound-GPTQ-4bit), [model-kaitchup-autogptq-int2*](https://beta-index.hf-mirror.com/kaitchup/Qwen2.5-72B-Instruct-AutoRound-GPTQ-2bit), [recipe](./docs/Qwen2.5-72B-Instruct-sym.md) |
+| meta-llama/Meta-Llama-3.1-70B-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Meta-Llama-3.1-70B-Instruct-int4-sym-inc), [model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Meta-Llama-3.1-70B-Instruct-int4-sym-inc),[model-opea-int4-asym-autoround](https://huggingface.co/OPEA/Meta-Llama-3.1-70B-Instruct-int4-asym-inc) |
+| meta-llama/Meta-Llama-3.1-8B-Instruct | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/Meta-Llama-3.1-8B-Instruct-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/Meta-Llama-3.1-8B-Instruct-int4-sym-inc),[model-kaitchup-autogptq-int4*](https://huggingface.co/kaitchup/Meta-Llama-3.1-8B-Instruct-autoround-gptq-4bit-asym), [model-kaitchup-autogptq-sym-int4*](https://huggingface.co/kaitchup/Meta-Llama-3.1-8B-Instruct-autoround-gptq-4bit-sym), [recipe](https://huggingface.co/Intel/Meta-Llama-3.1-8B-Instruct-int4-inc) |
+| meta-llama/Meta-Llama-3.1-8B | [model-kaitchup-autogptq-sym-int4*](https://huggingface.co/kaitchup/Meta-Llama-3.1-8B-autoround-gptq-4bit-sym) |
+| Qwen/Qwen-VL | [accuracy](./examples/multimodal-modeling/Qwen-VL/README.md), [recipe](./examples/multimodal-modeling/Qwen-VL/run_autoround.sh)
+| Qwen/Qwen2-7B | [model-autoround-sym-int4](https://huggingface.co/Intel/Qwen2-7B-int4-inc), [model-autogptq-sym-int4](https://huggingface.co/Intel/Qwen2-7B-int4-inc) |
+| THUDM/glm-4-9b-chat | [model-opea-int4-sym-autoround](https://huggingface.co/OPEA/glm-4-9b-chat-int4-sym-inc),[model-opea-int4-sym-autogptq](https://huggingface.co/OPEA/glm-4-9b-chat-int4-sym-inc) |
+| Qwen/Qwen2-57B-A14B-Instruct | [model-autoround-sym-int4](https://huggingface.co/Intel/Qwen2-57B-A14B-Instruct-int4-inc),[model-autogptq-sym-int4](https://huggingface.co/Intel/Qwen2-57B-A14B-Instruct-int4-inc) |
+| 01-ai/Yi-1.5-9B | [model-LnL-AI-autogptq-int4*](https://huggingface.co/LnL-AI/Yi-1.5-9B-4bit-gptq-autoround) |
+| 01-ai/Yi-1.5-9B-Chat | [model-LnL-AI-autogptq-int4*](https://huggingface.co/LnL-AI/Yi-1.5-9B-Chat-4bit-gptq-autoround) |
+| Intel/neural-chat-7b-v3-3 | [model-autogptq-int4](https://huggingface.co/Intel/neural-chat-7b-v3-3-int4-inc) |
+| Intel/neural-chat-7b-v3-1 | [model-autogptq-int4](https://huggingface.co/Intel/neural-chat-7b-v3-1-int4-inc) |
+| TinyLlama-1.1B-intermediate | [model-LnL-AI-autogptq-int4*](https://huggingface.co/LnL-AI/TinyLlama-1.1B-intermediate-step-1341k-3T-autoround-lm_head-symFalse) |
+| mistralai/Mistral-7B-v0.1 | [model-autogptq-lmhead-int4](https://huggingface.co/Intel/Mistral-7B-v0.1-int4-inc-lmhead), [model-autogptq-int4](https://huggingface.co/Intel/Mistral-7B-v0.1-int4-inc) |
+| google/gemma-2b | [model-autogptq-int4](https://huggingface.co/Intel/gemma-2b-int4-inc) |
+| tiiuae/falcon-7b | [model-autogptq-int4-G64](https://huggingface.co/Intel/falcon-7b-int4-inc) |
+| sapienzanlp/modello-italia-9b | [model-fbaldassarri-autogptq-int4*](https://huggingface.co/fbaldassarri/modello-italia-9b-autoround-w4g128-cpu) |
+| microsoft/phi-2 | [model-autoround-sym-int4](https://huggingface.co/Intel/phi-2-int4-inc) [model-autogptq-sym-int4](https://huggingface.co/Intel/phi-2-int4-inc) |
+| microsoft/Phi-3.5-mini-instruct | [model-kaitchup-autogptq-sym-int4*](https://huggingface.co/kaitchup/Phi-3.5-Mini-instruct-AutoRound-4bit) |
+| mistralai/Mistral-7B-Instruct-v0.2 | [outdated-recipe](./docs/Mistral-7B-Instruct-v0.2-asym-recipe.md) |
+| mistralai/Mixtral-8x7B-Instruct-v0.1 | [outdated-recipe](./docs/Mixtral-8x7B-Instruct-v0.1-asym-recipe.md) |
+| mistralai/Mixtral-8x7B-v0.1 | [outdated-recipe](./docs/Mixtral-8x7B-v0.1-asym-acc.md) |
+| meta-llama/Meta-Llama-3-8B-Instruct | [outdated-recipe](./docs/Meta-Llama-3-8B-Instruct-asym-recipe.md) |
+| google/gemma-7b | [outdated-recipe](./docs/gemma-7b-asym-recipe.md) |
+| meta-llama/Llama-2-7b-chat-hf | [outdated-recipe](./docs/Llama-2-7b-chat-hf-asym-recipe.md) |
+| baichuan-inc/Baichuan2-7B-Chat | [outdated-recipe](./docs/baichuan2-7b-cha-asym-recipe.md) |
+| 01-ai/Yi-6B-Chat | [outdated-recipe](./docs/Yi-6B-Chat-asym-recipe.md) |
+| facebook/opt-2.7b | [outdated-recipe](./docs/opt-2.7b-asym-recipe.md) |
+| bigscience/bloom-3b | [outdated-recipe](./docs/bloom-3B-asym-recipe.md) |
+| EleutherAI/gpt-j-6b | [outdated-recipe](./docs/gpt-j-6B-asym-recipe.md) |
## Integration
diff --git a/auto_round/backend.py b/auto_round/backend.py
index b5c1b075d..d64786123 100644
--- a/auto_round/backend.py
+++ b/auto_round/backend.py
@@ -13,25 +13,26 @@
# limitations under the License.
import functools
-import logging
from dataclasses import dataclass, field
from typing import List, Any, Optional
from transformers.utils.versions import require_version
-from auto_round.utils import get_library_version
+from auto_round.utils import get_library_version, logger
BackendInfos = {}
import cpuinfo
+
def get_cpu_manufacturer():
cpu_info = cpuinfo.get_cpu_info()
- if "brand_raw" in cpu_info and "intel" in cpu_info["brand_raw"].lower():
+ if "brand_raw" in cpu_info and "intel" in cpu_info["brand_raw"].lower():
return "intel"
else:
return "others"
+
@dataclass
class BackendInfo:
"""Stores configuration details for various backend formats.
@@ -79,6 +80,17 @@ def feature_num_greater_checker(in_feature, out_feature, num):
return in_feature * out_feature > num
[email protected]_cache(None)
+def check_auto_round_exllamav2_installed():
+ try:
+ from autoround_exllamav2_kernels import gemm_half_q_half, make_q_matrix
+ except ImportError:
+ return False, ("please install from source to enable auto-round exllamav2 kernel."
+ "`git clone https://github.com/intel/auto-round && cd auto-round &&"
+ " pip install -vvv --no-build-isolation -e .`")
+ return True, ""
+
+
feature_multiply_checker_32 = functools.partial(feature_multiply_checker, in_feature_multiplier=32)
feature_multiply_checker_marlin = functools.partial(feature_multiply_checker, in_feature_multiplier=128,
@@ -91,7 +103,8 @@ BackendInfos['auto_round:exllamav2'] = BackendInfo(device=["cuda"], sym=[True, F
bits=[4], group_size=None,
priority=5,
feature_checks=[feature_multiply_checker_32],
- alias=["auto_round"]
+ alias=["auto_round"],
+ requirements=[check_auto_round_exllamav2_installed]
)
BackendInfos['auto_round:tritonv2'] = BackendInfo(device=["cuda"], sym=[True, False],
@@ -117,24 +130,24 @@ BackendInfos['gptq:tritonv2'] = BackendInfo(device=["cuda"], sym=[True, False],
priority=0, feature_checks=[feature_multiply_checker_32],
alias=["auto_round:gptq:tritonv2", "auto_round:auto_gptq:tritonv2",
"auto_gptq:tritonv2"],
- requirements=["auto-gptq>=0.7.1","triton<3.0,>=2.0"]
+ requirements=["auto-gptq>=0.7.1", "triton<3.0,>=2.0"]
)
BackendInfos['gptq:cuda'] = BackendInfo(device=["cuda"], sym=[True, False],
- packing_format="triton_zp+-1",
- bits=[2, 3, 4, 8], group_size=None,
- priority=1, feature_checks=[feature_multiply_checker_32],
- alias=["auto_round:auto_gptq:cuda,auto_gptq:cuda, auto_round:gptq:cuda"],
- convertable_format=["triton_zp+-1"],
- requirements=["auto-gptq>=0.7.1"]
- )
+ packing_format="triton_zp+-1",
+ bits=[2, 3, 4, 8], group_size=None,
+ priority=1, feature_checks=[feature_multiply_checker_32],
+ alias=["auto_round:auto_gptq:cuda,auto_gptq:cuda, auto_round:gptq:cuda"],
+ convertable_format=["triton_zp+-1"],
+ requirements=["auto-gptq>=0.7.1"]
+ )
BackendInfos['awq:gemm'] = BackendInfo(device=["cuda"], sym=[True, False], ##actrally is gemm
packing_format="awq",
bits=[4], group_size=None,
priority=4, feature_checks=[feature_num_greater_checker_1024],
alias=["auto_awq:gemm", "auto_round:awq:gemm", "auto_round:auto_awq:gemm", "awq",
- "auto_awq", "auto_round:awq", "aut_round:auto_awq"],
+ "auto_awq", "auto_round:awq", "auto_round:auto_awq"],
requirements=["autoawq"]
)
@@ -156,23 +169,23 @@ BackendInfos['auto_round:qbits_zp'] = BackendInfo(device=["cpu"], sym=[True, Fal
)
BackendInfos['auto_round:ipex_gptq'] = BackendInfo(device=["cpu"], sym=[True, False],
- packing_format="ipex_gptq",
- bits=[4], group_size=None,
- priority=5 if "intel" in get_cpu_manufacturer() else 5,
- feature_checks=[],
- convertable_format=["triton_zp+-1"],
- requirements=["intel-extension-for-pytorch>=2.4"]
- )
+ packing_format="ipex_gptq",
+ bits=[4], group_size=None,
+ priority=5 if "intel" in get_cpu_manufacturer() else 5,
+ feature_checks=[],
+ convertable_format=["triton_zp+-1"],
+ requirements=["intel-extension-for-pytorch>=2.4"]
+ )
BackendInfos['auto_round:ipex_awq'] = BackendInfo(device=["cpu"], sym=[True, False],
- packing_format="ipex_awq",
- bits=[4], group_size=None,
- priority=5 if "intel" in get_cpu_manufacturer() else 5,
- feature_checks=[],
- ##convertable_format=["triton_zp+-1", "awq"],
- convertable_format=["awq"],
- requirements=["intel-extension-for-pytorch>=2.4"]
- )
+ packing_format="ipex_awq",
+ bits=[4], group_size=None,
+ priority=5 if "intel" in get_cpu_manufacturer() else 5,
+ feature_checks=[],
+ ##convertable_format=["triton_zp+-1", "awq"],
+ convertable_format=["awq"],
+ requirements=["intel-extension-for-pytorch>=2.4"]
+ )
# BackendInfos['auto_round:marlin'] = BackendInfo(device=["gpu"], sym=[True],
# packing_format="marlin",
@@ -256,10 +269,14 @@ def check_compatible(backend_name, device, bits, group_size, sym, packing_format
if check_requirements and backend.requirements is not None:
for requirement in backend.requirements:
- try:
- require_version(requirement)
- except ImportError:
- return False
+ if isinstance(requirement, str):
+ try:
+ require_version(requirement)
+ except ImportError:
+ return False
+ else:
+ res, _ = requirement()
+ return res
return True
@@ -507,8 +524,16 @@ def get_layer_backend(device, backend, orig_backend, bits, group_size, sym, in_f
key=lambda support_backend: BackendInfos[support_backend].priority,
reverse=True)
backend_info = BackendInfos[supported_backends_need_package[0]]
- str_info = ",".join(backend_info.requirements)
- logging.error(f"`pip install {str_info}` to support inference")
+ logger.error("please install all the following packages to support inference")
+ for requirement in backend_info.requirements:
+ if isinstance(requirement, str):
+ try:
+ require_version(requirement)
+ except ImportError:
+ logger.error(f"pip install {requirement}")
+ else:
+ str_info = requirement()[1]
+ logger.error(str_info)
exit(-1)
raise ValueError(f"None of the backends support this layer")
diff --git a/auto_round/export/export_to_autogptq/export.py b/auto_round/export/export_to_autogptq/export.py
index a35117481..bc7bfd715 100644
--- a/auto_round/export/export_to_autogptq/export.py
+++ b/auto_round/export/export_to_autogptq/export.py
@@ -45,7 +45,6 @@ import os
import torch.nn as nn
import transformers
-from auto_round.export.register import register_format
import threadpoolctl as tctl
import inspect
from tqdm import tqdm
diff --git a/auto_round/export/export_to_awq/export.py b/auto_round/export/export_to_awq/export.py
index 09f454837..b82297c60 100644
--- a/auto_round/export/export_to_awq/export.py
+++ b/auto_round/export/export_to_awq/export.py
@@ -18,28 +18,16 @@
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
-# MIT License
-# Copyright (c) 2023 MIT HAN Lab
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-# The above copyright notice and this permission notice shall be included in all
-# copies or substantial portions of the Software.
import os
-from os.path import isdir, isfile, join
import torch
import torch.nn as nn
-from auto_round.export.register import register_format
-from auto_round.utils import convert_dtype_torch2str_hf, logger, get_module, set_module
+
+from auto_round.utils import logger, get_module, set_module, check_to_quantized
import copy
import json
-from typing import Dict, List, Optional, Union
-from .utils import WQLinear_GEMM, clear_memory, get_self_modules
+from .utils import WQLinear_GEMM, clear_memory
from concurrent.futures import ThreadPoolExecutor
import threadpoolctl as tctl
from tqdm import tqdm
@@ -81,15 +69,7 @@ def save_quantized_as_autoawq(output_dir, inplace=True, **kwargs):
"""Export the model to autogptq format to easily leverage cuda kernel."""
model = kwargs["model"]
layer_config = kwargs["layer_config"]
- sym = kwargs["sym"]
- bits = kwargs["bits"]
- group_size = kwargs["group_size"]
- iters = kwargs["iters"]
- lr = kwargs["lr"]
- minmax_lr = kwargs["minmax_lr"]
- enable_minmax_tuning = kwargs["enable_minmax_tuning"]
- enable_quanted_input = kwargs["enable_quanted_input"]
- scale_dtype = kwargs["scale_dtype"]
+
tokenizer = kwargs.get("tokenizer", None)
processor = kwargs.get("processor", None)
@@ -98,8 +78,7 @@ def save_quantized_as_autoawq(output_dir, inplace=True, **kwargs):
tokenizer.save_pretrained(output_dir)
if processor is not None:
processor.save_pretrained(output_dir)
- ##check module quantized in block, this may have bug for mixed precision quantization
- modules_to_not_convert = []
+
if inplace:
compressed_model = model.to("cpu")
else:
@@ -107,18 +86,6 @@ def save_quantized_as_autoawq(output_dir, inplace=True, **kwargs):
names = list(layer_config.keys())
- self_modules = get_self_modules(compressed_model)
- layers = []
- for i in range(len(self_modules)):
- module = self_modules[i]
- named_linears = get_named_linears(module)
- for name, linear_layer in named_linears.items():
- key = get_module_name(compressed_model, linear_layer)
- layers.append(key)
- config = layer_config[key]
- if config["bits"] > 8:
- modules_to_not_convert.append(name)
-
backend = None
with ThreadPoolExecutor(max_workers=2) as executor:
with tqdm(total=len(names), leave=True) as pbar:
@@ -130,126 +97,52 @@ def save_quantized_as_autoawq(output_dir, inplace=True, **kwargs):
if output_dir is None:
return model
- quant_config = {}
- quant_config["quant_method"] = "awq"
- quant_config["modules_to_not_convert"] = None
- quant_config["version"] = "gemm"
- quant_config["iters"] = iters
- quant_config["lr"] = lr
- quant_config["minmax_lr"] = minmax_lr
- quant_config["enable_minmax_tuning"] = enable_minmax_tuning
- quant_config["enable_quanted_input"] = enable_quanted_input
- quant_config["scale_dtype"] = convert_dtype_torch2str_hf(scale_dtype)
- quant_config["sym"] = sym
- quant_config["bits"] = bits
- quant_config["group_size"] = group_size
- quant_config["zero_point"] = not sym
+ quantization_config = kwargs["serialization_dict"]
+
if output_dir is None:
return compressed_model
- save_quantized(compressed_model, save_dir=output_dir, quant_config=quant_config)
- return compressed_model
+ modules_to_not_convert = []
+ layer_config = kwargs["layer_config"]
+ for key in layer_config.keys():
+ if not check_to_quantized(layer_config[key]):
+ modules_to_not_convert.append(key)
+ quantization_config["quant_method"] = "awq"
+ quantization_config["zero_point"] = not quantization_config["sym"]
+ quantization_config["version"] = "gemm"
+
+ quantization_config["modules_to_not_convert"] = modules_to_not_convert
+ ##check module quantized in block, this may have bug for mixed precision quantization
+ if hasattr(model, "config"):
+ model.config.quantization_config = quantization_config
+ save(compressed_model, output_dir, safe_serialization=True)
-from safetensors.torch import save_file
-from transformers.modeling_utils import shard_checkpoint
-
-
-def save_quantized(
- model,
- save_dir,
- quant_config,
- safetensors=True,
- shard_size="5GB",
-):
- save_dir = save_dir[:-1] if save_dir[-1] == "/" else save_dir
-
- # Save model
- class EmptyModule(nn.Module):
- def __init__(self):
- super(EmptyModule, self).__init__()
-
- def forward(self, x):
- return x
-
- # Save model and config files with empty state dict
- awq_quant_config = {
- "quant_method": "awq",
- "zero_point": quant_config["zero_point"],
- "group_size": quant_config["group_size"],
- "bits": quant_config["bits"],
- "version": "gemm",
- "modules_to_not_convert": quant_config["modules_to_not_convert"],
- }
-
- model.config.quantization_config = awq_quant_config
- model.generation_config.do_sample = True
- model.save_pretrained(save_dir, state_dict=EmptyModule().state_dict())
-
- # Remove empty state dict
- default_paths = [
- f"{save_dir}/model.safetensors",
- f"{save_dir}/pytorch_model.bin",
- ]
- for path in default_paths:
- if os.path.exists(path):
- os.remove(path)
-
- # model_name has no extension, add it when saving state_dict
- model_name = "model.safetensors" if safetensors else "pytorch_model.bin"
-
- # shard checkpoint into chunks (10GB default)
- shards, index = shard_checkpoint(model.state_dict(), max_shard_size=shard_size, weights_name=model_name)
-
- for shard_file, shard in shards.items():
- if safetensors:
- # safetensors must be in the same memory, so we duplicate and use contiguous memory
- shard = {k: v.clone().contiguous() for k, v in shard.items()}
- save_file(shard, os.path.join(save_dir, shard_file), metadata={"format": "pt"})
- else:
- torch.save(shard, os.path.join(save_dir, shard_file))
-
- # save shard index
- if index is not None:
- with open(f"{save_dir}/{model_name}.index.json", "w+") as file:
- file.write(json.dumps(index, indent=4))
-
- # save quantize_config
- with open(join(save_dir, "quantization_config.json"), "w", encoding="utf-8") as f:
- json.dump(quant_config, f, indent=2)
-
-
-def get_named_linears(module):
- """Get the name, linear_op pairs of a given module.
- Args:
- module: A module to be searched.
- """
- return {name: m for name, m in module.named_modules() if isinstance(m, torch.nn.Linear)}
-
-
-def set_op_by_name(layer, name, new_module):
- levels = name.split(".")
- if len(levels) > 1:
- mod_ = layer
- for l_idx in range(len(levels) - 1):
- if levels[l_idx].isdigit():
- mod_ = mod_[int(levels[l_idx])]
- else:
- mod_ = getattr(mod_, levels[l_idx])
- setattr(mod_, levels[-1], new_module)
- else:
- setattr(layer, name, new_module)
+ return compressed_model
-def get_module_name(model, module_to_find):
- """Get the name of a given module in a model.
+def save(model: nn.Module, save_dir: str, max_shard_size: str = "5GB", safe_serialization: bool = True):
+ """Save model state dict and configs.
+
Args:
- model: The model.
- module_to_find: A module to be found.
- Returns:
- name: The corresponding name of the given module.
+ 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`).
"""
- for name, module in model.named_modules():
- if module is module_to_find:
- return name
- return None
-
+ os.makedirs(save_dir, exist_ok=True)
+ model.save_pretrained(save_dir, max_shard_size=max_shard_size, safe_serialization=safe_serialization)
+ 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)
diff --git a/auto_round/export/export_to_awq/utils.py b/auto_round/export/export_to_awq/utils.py
index 5dcaf0ef0..f4f45bf0e 100644
--- a/auto_round/export/export_to_awq/utils.py
+++ b/auto_round/export/export_to_awq/utils.py
@@ -59,8 +59,10 @@ def unpack_awq(qweight: torch.Tensor, qzeros: torch.Tensor, bits: int):
return iweights, izeros
+
AWQ_REVERSE_ORDER = [0, 4, 1, 5, 2, 6, 3, 7]
+
def reverse_awq_order(iweights: torch.Tensor, izeros: torch.Tensor, bits: int):
reverse_order_tensor = torch.arange(
iweights.shape[-1],
@@ -85,8 +87,8 @@ def dequantize_gemm(qweight, qzeros, scales, bits, group_size):
iweight, izeros = reverse_awq_order(iweight, izeros, bits)
# overflow checks
- iweight = torch.bitwise_and(iweight, (2**bits) - 1)
- izeros = torch.bitwise_and(izeros, (2**bits) - 1)
+ iweight = torch.bitwise_and(iweight, (2 ** bits) - 1)
+ izeros = torch.bitwise_and(izeros, (2 ** bits) - 1)
# fp16 weights
scales = scales.repeat_interleave(group_size, dim=0)
@@ -109,15 +111,15 @@ class WQLinearMMFunction(Function):
@staticmethod
# ctx is the first argument to forward
def forward(
- ctx,
- x,
- qweight,
- qzeros,
- scales,
- w_bit=4,
- group_size=128,
- bias=None,
- out_features=0,
+ ctx,
+ x,
+ qweight,
+ qzeros,
+ scales,
+ w_bit=4,
+ group_size=128,
+ bias=None,
+ out_features=0,
):
# The forward pass can use ctx.
ctx.save_for_backward(x, qweight, qzeros, scales, bias)
@@ -141,7 +143,7 @@ class WQLinearMMFunction(Function):
class WQLinear_GEMM(nn.Module):
def __init__(
- self, w_bit, group_size, in_features, out_features, bias, dev, training=False
+ self, w_bit, group_size, in_features, out_features, bias, dev, training=False
):
super().__init__()
@@ -196,7 +198,7 @@ class WQLinear_GEMM(nn.Module):
@classmethod
def from_linear(
- cls, linear, w_bit, group_size, init_only=False, scales=None, zeros=None
+ cls, linear, w_bit, group_size, init_only=False, scales=None, zeros=None
):
awq_linear = cls(
w_bit,
@@ -329,58 +331,3 @@ def clear_memory(weight=None):
del weight
gc.collect()
torch.cuda.empty_cache()
-
-
-MODEL_LAYERS_BY_MODEL_TYPE = {
- 'aquila': 'model.layers',
- 'baichuan': 'model.layers',
- 'bloom': 'transformer.h',
- 'cohere': 'model.layers',
- 'deepseek_v2': 'model.layers',
- 'falcon': 'transformer.h',
- 'gemma': 'model.layers',
- 'gemma2': 'model.layers',
- 'gpt2': 'transformer.h',
- 'gpt_bigcode': 'transformer.h',
- 'gpt_neo': 'transformer.h',
- 'gpt_neox': 'gpt_neox.layers',
- 'gptj': 'transformer.h',
- 'internlm2': 'model.layers',
- 'llama': 'model.layers',
- 'llava': 'language_model.model.layers',
- 'llava_next': 'language_model.model.layers',
- 'minicpm': 'model.layers',
- 'mistral': 'model.layers',
- 'mixtral': 'model.layers',
- 'mpt': 'transformer.blocks',
- 'opt': 'model.decoder.layers',
- 'phi': 'model.layers',
- 'phi3': 'model.layers',
- 'qwen': 'transformer.h',
- 'qwen2': 'model.layers',
- 'roberta': 'roberta.encoder',
- 'stablelm': 'model.layers',
- 'starcoder2': 'model.layers',
- 'xlm-roberta': 'roberta.encoder',
- 'yi': 'model.layers',
-}
-
-def get_self_modules(model):
- def _get(model, self_modules):
- module = model
- for m in self_modules.split('.'):
- module = getattr(module, m)
- return module
-
- model_type = model.config.model_type
- if model_type not in MODEL_LAYERS_BY_MODEL_TYPE:
- for tmp_self_modules in set(MODEL_LAYERS_BY_MODEL_TYPE.values()):
- try:
- return _get(model, tmp_self_modules)
- except:
- continue
- warnings.warn(f"Model type {model_type} may be not supported by auto_awq,"
- " please checkout the auto_awq repository.")
- return None
- self_modules = MODEL_LAYERS_BY_MODEL_TYPE.get(model_type)
- return _get(model, self_modules)
diff --git a/auto_round/script/llm.py b/auto_round/script/llm.py
index 8e92021c0..4e4a10cba 100644
--- a/auto_round/script/llm.py
+++ b/auto_round/script/llm.py
@@ -27,7 +27,7 @@
# limitations under the License.
import argparse
-from auto_round.utils import detect_device
+from auto_round.utils import detect_device, set_layer_config_by_fp_layers
class BasicArgumentParser(argparse.ArgumentParser):
@@ -376,21 +376,16 @@ def tune(args):
" resulting in an exporting issue to autogptq")
layer_config = {}
- if args.fp_layers != "":
- fp_layers = args.fp_layers.replace(" ", "").split(",")
- for n, m in model.named_modules():
- if not isinstance(m, (torch.nn.Linear, transformers.modeling_utils.Conv1D)):
- continue
- for fp_layer in fp_layers:
- if fp_layer in n:
- layer_config[n] = {"bits": 16}
- logger.info(
- f"{n} will not be quantized.")
- if len(layer_config) > 0:
- for format in formats:
- if "auto_round" not in format and "fake" not in format:
- ##TODO gptq, awq could support some mixed precision config
- logger.warning(f"mixed precision exporting does not support {format} currently")
+ not_quantize_layer_names = set_layer_config_by_fp_layers(model, args.fp_layers)
+ for name in not_quantize_layer_names:
+ layer_config[name] = {"bits": 16}
+ if len(not_quantize_layer_names) > 0:
+ logger.info(
+ f"{not_quantize_layer_names} will not be quantized.")
+ for format in formats:
+ if "auto_round" not in format and "fake" not in format and "awq" not in format:
+ ##TODO gptq could support some mixed precision config
+ logger.warning(f"mixed precision exporting does not support {format} currently")
lm_head_layer_name = "lm_head"
for n, _ in model.named_modules():
diff --git a/auto_round/script/mllm.py b/auto_round/script/mllm.py
index 1b9a81a9a..825bf1c84 100644
--- a/auto_round/script/mllm.py
+++ b/auto_round/script/mllm.py
@@ -24,7 +24,7 @@ os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
torch.use_deterministic_algorithms(True, warn_only=True)
from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig, AutoProcessor
-from auto_round.utils import detect_device
+from auto_round.utils import detect_device, set_layer_config_by_fp_layers
from auto_round.utils import logger
@@ -322,6 +322,18 @@ def tune(args):
round = AutoRoundMLLM
+ layer_config = {}
+ not_quantize_layer_names = set_layer_config_by_fp_layers(model, args.fp_layers)
+ for name in not_quantize_layer_names:
+ layer_config[name] = {"bits": 16}
+ if len(not_quantize_layer_names) > 0:
+ logger.info(
+ f"{not_quantize_layer_names} will not be quantized.")
+ for format in formats:
+ if "auto_round" not in format and "fake" not in format and "awq" not in format:
+ ##TODO gptq could support some mixed precision config
+ logger.warning(f"mixed precision exporting does not support {format} currently")
+
layer_config = {}
if args.fp_layers != "":
fp_layers = args.fp_layers.replace(" ", "").split(",")
diff --git a/auto_round/utils.py b/auto_round/utils.py
index c5cb87747..cce826468 100644
--- a/auto_round/utils.py
+++ b/auto_round/utils.py
@@ -36,6 +36,7 @@ from .special_model_handler import shareable_keywords
def warning_once(self, msg: str):
self.warning(msg)
+
class AutoRoundFormatter(logging.Formatter):
grey = "\x1b[38;20m"
yellow = "\x1b[33;1m"
@@ -57,6 +58,7 @@ class AutoRoundFormatter(logging.Formatter):
formatter = logging.Formatter(log_fmt, "%Y-%m-%d %H:%M:%S")
return formatter.format(record)
+
logging.Logger.warning_once = warning_once
logger = logging.getLogger("autoround")
logger.setLevel(logging.INFO)
@@ -309,7 +311,7 @@ def validate_modules(module_names, quant_vision=False, vison_blocks_names=None):
" as dependent, {shortest_module} and {longest_module}")
flag = False
if quant_vision:
- for n,_ in module_names:
+ for n, _ in module_names:
flag = any(key not in n.lower() for key in (vison_blocks_names))
if quant_vision and not flag:
raise ValueError(f"Cannot find the visual block. Please reset the quant_nontext_module parameter to False, " \
@@ -332,7 +334,7 @@ def find_matching_blocks(model, all_blocks, to_quant_block_names):
if not to_quant_block_names:
return all_blocks
to_quant_block_list = to_quant_block_names
- if isinstance(to_quant_block_names, list) or isinstance(to_quant_block_names,tuple):
+ if isinstance(to_quant_block_names, list) or isinstance(to_quant_block_names, tuple):
return to_quant_block_names
if isinstance(to_quant_block_names, str):
to_quant_block_list = [name.strip() for name in to_quant_block_names.split(",")]
@@ -349,8 +351,8 @@ def find_matching_blocks(model, all_blocks, to_quant_block_names):
raise ValueError("No block names matched. Please check the input for to_quant_block_name," \
"or set to_quant_block_name to None to automatically match quantizable blocks.")
return target_blocks
-
-
+
+
def get_block_names(model):
"""Get the block names for transformers-like networks.
@@ -491,7 +493,7 @@ def check_to_quantized(config):
False otherwise.
"""
if isinstance(config, dict):
-
+
if int(config["bits"]) > 8:
return False
return True
@@ -967,7 +969,7 @@ def compile_func_on_hpu(func):
def compile_func_on_cuda_or_cpu(func, enable_torch_compile):
- if enable_torch_compile or (TORCH_VERSION_AT_LEAST_2_6_PRE_RELEASE and enable_torch_compile!=False):
+ if enable_torch_compile or (TORCH_VERSION_AT_LEAST_2_6_PRE_RELEASE and enable_torch_compile != False):
return torch.compile(func)
else:
return func
@@ -980,7 +982,6 @@ def compile_func(fun, device, enable_torch_compile):
return compile_func_on_cuda_or_cpu(fun, enable_torch_compile)
-
def is_numba_available(): # pragma: no cover
"""Check if Numba is available."""
try:
@@ -1030,6 +1031,7 @@ def is_tbb_available(): # pragma: no cover
return False
return True
+
def can_pack_with_numba(): # pragma: no cover
"""Check if Numba and TBB are available for packing.
@@ -1041,3 +1043,41 @@ def can_pack_with_numba(): # pragma: no cover
if not is_tbb_available():
return False
return True
+
+
+def set_layer_config_by_fp_layers(model, fp_layers):
+ """Identifies and returns layers in the model to exclude from quantization.
+
+ This function processes a comma-separated list of fully precision (FP) layers,
+ matches them to the names of layers in the model, and returns a list of such
+ layers to exclude from quantization.
+
+ Args:
+ model (torch.nn.Module): The model whose layers will be inspected.
+ fp_layers (str): A comma-separated string of layer names to be excluded
+ from quantization. Whitespace is ignored in this string.
+
+ Returns:
+ list: A list of layer names that match the specified FP layers or are
+ subcomponents of those layers.
+ """
+ fp_layers = fp_layers.replace(" ", "").split(",")
+ all_layer_names = []
+ for n, m in model.named_modules():
+ if isinstance(m, (torch.nn.Linear, transformers.modeling_utils.Conv1D)):
+ all_layer_names.append(n)
+ not_to_quantized_layers = []
+
+ for fp_layer in fp_layers:
+ if fp_layer == "":
+ continue
+ if fp_layer in all_layer_names:
+ not_to_quantized_layers.append(fp_layer)
+ continue
+ if fp_layer[-1] != ".":
+ fp_layer = fp_layer + "." ##ticky setting
+ for name in all_layer_names:
+ if fp_layer in name:
+ not_to_quantized_layers.append(name)
+
+ return not_to_quantized_layers