InternLM / lmdeploy

LMDeploy is a toolkit for compressing, deploying, and serving LLMs.
https://lmdeploy.readthedocs.io/en/latest/
Apache License 2.0
4.63k stars 426 forks source link

[Bug] Qwen/Qwen2-72B-Instruct AWQ Quantization NaN Error #1786

Open serser opened 5 months ago

serser commented 5 months ago

Checklist

Describe the bug

When quantizing Qwen2-72B-Instruct, it fails with the assertion at this layer model.layers.2.mlp.gate_proj by,

assert torch.isnan(p).sum() == 0

I tried --search-scale from the issue #1656, which runs into the same error.

It turns out that when calculating weight scales, many groups of weights happen to be all zeros which caused zero division. I changed to the following to avoid it,

@torch.no_grad()
def get_weight_scale(weight, q_group_size=-1):
    org_shape = weight.shape
    if q_group_size > 0:
        weight = weight.view(-1, q_group_size)
    # scale = weight.abs() / (weight.abs().amax(dim=1, keepdim=True))
    epsilon = 1e-6
    max_abs = weight.abs() + epsilon
    scale = weight.abs() / max_abs.amax(dim=1, keepdim=True)
    scale = scale.view(org_shape)
    scale = scale.mean(0)
    return scale

A similar assertion happens when calculating smoothed scales here, I changed into the following,

    concat_w = torch.cat([fc.weight for fc in fcs], dim=0)
    w_scales = get_weight_scale(concat_w, group_size)

    # fix div by zero
    zero_mask = (w_scales == 0)
    if zero_mask.any():
        w_scales[zero_mask] = 1e-6

    scales = (act_scales.pow(alpha) /
              w_scales.pow(1 - alpha)).clamp(min=1e-4).to(device).to(dtype)
    scales = scales / (scales.max() * scales.min()).sqrt()

    # fix div by zero
    zero_mask = (scales == 0)
    if zero_mask.any():
        scales[zero_mask] = 1

Then the quantization went without error. I haven't checked the accuracy of the model yet. Please correct me I've made mistakes.

Reproduction

lmdeploy lite auto_awq /path/to/Qwen2-72B-Instruct \
 --calib-dataset c4 --calib-samples 32 --calib-seqlen 512 --w-bits 4 --w-group-size 128 \
 --work-dir /path/to/Qwen2-72B-Instruct-Quant 

Environment

sys.platform: linux
Python: 3.8.18 (default, Sep 11 2023, 13:40:15) [GCC 11.2.0]
CUDA available: True
MUSA available: False
numpy_random_seed: 2147483648
GPU 0,1: NVIDIA A100-SXM4-80GB
CUDA_HOME: /usr/local/cuda
NVCC: Cuda compilation tools, release 11.7, V11.7.99
GCC: gcc (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)
PyTorch: 2.2.1+cu118
PyTorch compiling details: PyTorch built with:
  - GCC 9.3
  - C++ Version: 201703
  - Intel(R) oneAPI Math Kernel Library Version 2022.2-Product Build 20220804 for Intel(R) 64 architecture applications
  - Intel(R) MKL-DNN v3.3.2 (Git Hash 2dc95a2ad0841e29db8b22fbccaf3e5da7992b01)
  - OpenMP 201511 (a.k.a. OpenMP 4.5)
  - LAPACK is enabled (usually provided by MKL)
  - NNPACK is enabled
  - CPU capability usage: AVX2
  - CUDA Runtime 11.8
  - NVCC architecture flags: -gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_37,code=sm_37;-gencode;arch=compute_90,code=sm_90
  - CuDNN 8.9.2  (built against CUDA 12.1)
    - Built with CuDNN 8.7
  - Magma 2.6.1
  - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, CUDA_VERSION=11.8, CUDNN_VERSION=8.7.0, CXX_COMPILER=/opt/rh/devtoolset-9/root/usr/bin/c++, CXX_FLAGS= -D_GLIBCXX_USE_CXX11_ABI=0 -fabi-version=11 -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DUSE_FBGEMM -DUSE_QNNPACK -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-type-limits -Wno-array-bounds -Wno-unknown-pragmas -Wno-unused-parameter -Wno-unused-function -Wno-unused-result -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=pedantic -Wno-error=old-style-cast -Wno-missing-braces -fdiagnostics-color=always -faligned-new -Wno-unused-but-set-variable -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, PERF_WITH_AVX512=1, TORCH_VERSION=2.2.1, USE_CUDA=ON, USE_CUDNN=ON, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, 

TorchVision: 0.17.1+cu118
LMDeploy: 0.4.2+0b4660c
transformers: 4.40.0
gradio: Not Found
fastapi: 0.110.2
pydantic: 2.7.0
triton: 2.2.0

Error traceback

No response

QwertyJack commented 5 months ago

Btw, Qwen has provided the AWQ quant version: https://huggingface.co/Qwen/Qwen2-72B-Instruct-AWQ

serser commented 5 months ago

Btw, Qwen has provided the AWQ quant version: https://huggingface.co/Qwen/Qwen2-72B-Instruct-AWQ

Cool, is it directly loadable from LMDeploy?

serser commented 5 months ago

An update, the quantized model can be loaded with lmdeploy chat ./Qwen2-72B-Instruct-Quant and it is automatically converted into TurboMind. This model chats fluently when I say hi.

linyubupa commented 4 months ago

An update, the quantized model can be loaded with lmdeploy chat ./Qwen2-72B-Instruct-Quant and it is automatically converted into TurboMind. This model chats fluently when I say hi.

when I load /Qwen2-72B-Instruct-awq , i encountered KeyError: 'model.layers.0.mlp.gate_proj.scales' , have you solved it

AllentDan commented 4 months ago

Add --model-format awq please.

linyubupa commented 4 months ago

Add --model-format awq please.

this is my command : lmdeploy serve api_server /yzwl_data/yumu/lmdeploy/lmdeploy/lite/apis/qwen2-7b-w8 --log-level INFO --backend turbomind --model-format awq --model-name qwen --server-port 23334 --tp 2 --max-batch-size 4 --quant-policy 8

and this is the error backtrace : Traceback (most recent call last): File "/opt/conda/bin/lmdeploy", line 8, in sys.exit(run()) File "/opt/conda/lib/python3.10/site-packages/lmdeploy/cli/entrypoint.py", line 37, in run args.run(args) File "/opt/conda/lib/python3.10/site-packages/lmdeploy/cli/serve.py", line 303, in api_server run_api_server(args.model_path, File "/opt/conda/lib/python3.10/site-packages/lmdeploy/serve/openai/api_server.py", line 1191, in serve VariableInterface.async_engine = pipeline_class( File "/opt/conda/lib/python3.10/site-packages/lmdeploy/serve/async_engine.py", line 206, in init self._build_turbomind(model_path=model_path, File "/opt/conda/lib/python3.10/site-packages/lmdeploy/serve/async_engine.py", line 253, in _build_turbomind self.engine = tm.TurboMind.from_pretrained( File "/opt/conda/lib/python3.10/site-packages/lmdeploy/turbomind/turbomind.py", line 387, in from_pretrained return cls(model_path=pretrained_model_name_or_path, File "/opt/conda/lib/python3.10/site-packages/lmdeploy/turbomind/turbomind.py", line 161, in init self.model_comm = self._from_hf(model_source=model_source, File "/opt/conda/lib/python3.10/site-packages/lmdeploy/turbomind/turbomind.py", line 270, in _from_hf output_model = OUTPUT_MODELS.get(output_format)( File "/opt/conda/lib/python3.10/site-packages/lmdeploy/turbomind/deploy/target_model/w4.py", line 80, in init super().init(input_model, cfg, to_file, out_dir) File "/opt/conda/lib/python3.10/site-packages/lmdeploy/turbomind/deploy/target_model/base.py", line 156, in init self.cfg = self.get_config(cfg) File "/opt/conda/lib/python3.10/site-packages/lmdeploy/turbomind/deploy/target_model/w4.py", line 92, in getconfig w1s, , _ = bin.ffn_scale(i) File "/opt/conda/lib/python3.10/site-packages/lmdeploy/turbomind/deploy/source_model/llama_awq.py", line 52, in ffn_scale return ensure_fp16orint32(self._ffn(i, 'scales')) File "/opt/conda/lib/python3.10/site-packages/lmdeploy/turbomind/deploy/source_model/llama.py", line 99, in _ffn tensor = self.params[ KeyError: 'model.layers.0.mlp.gate_proj.scales'

AllentDan commented 4 months ago

w8? Only w4a16 supported for turbomind engine. If you want to run w8a8, please add --backend pytorch to run pytorch engine.

serser commented 4 months ago

Update again. Although tp=1 works for the quantized model, when I try to convert it to tp=2, it runs into the following error since the first dimension of layers.0.feed_forward.w2.scales_zeros is an odd number 231. From here I see that the dimension to split is fixed for the scales. Any help to circumvent this issue?

+-------+---------+-----------------------------------------------------------------------------------------------------------------------------------+
| Model | Version | Status                                                                                                                            |
+-------+---------+-----------------------------------------------------------------------------------------------------------------------------------+
| qwen  | 1       | UNAVAILABLE: Internal: AssertionError: ('layers.0.feed_forward.w2.scales_zeros', 0, torch.Size([231, 8192]))                      |
|       |         |                                                                                                                                   |
|       |         | At:                                                                                                                               |
|       |         |   /home/me/qwen-2-72b-instruct/venv2/lib/python3.9/site-packages/lmdeploy/turbomind/deploy/target_model/base |
|       |         | .py(247): save_split                                                                                                              |
|       |         |   /home/me/qwen-2-72b-instruct/venv2/lib/python3.9/site-packages/lmdeploy/turbomind/deploy/target_model/base |
|       |         | .py(274): export                                                                                                                  |
|       |         |   /home/me/qwen-2-72b-instruct/venv2/lib/python3.9/site-packages/lmdeploy/turbomind/turbomind.py(161): __ini |
|       |         | t__                                                                                                                               |
|       |         |   /home/me/qwen-2-72b-instruct/venv2/lib/python3.9/site-packages/lmdeploy/serve/async_engine.py(253): _build |
|       |         | _turbomind                                                                                                                        |
|       |         |   /home/me/qwen-2-72b-instruct/venv2/lib/python3.9/site-packages/lmdeploy/turbomind/turbomind.py(161): __init__ |
|       |         |   /home/me/qwen-2-72b-instruct/venv2/lib/python3.9/site-packages/lmdeploy/turbomind/turbomind.py(387): from_pretrained |
|       |         |   /home/me/qwen-2-72b-instruct/venv2/lib/python3.9/site-packages/lmdeploy/serve/async_engine.py(253): _build_turbomind |
+-------+---------+-----------------------------------------------------------------------------------------------------------------------------------+
AllentDan commented 4 months ago

Currently, lmdeploy only supports group_size 128.