Skip to content

[BUG] OPT-125m not working after quantization  #1486

Closed

Description

@upunaprosk

Describe the bug

Small model opt-125m not working after quantization.

GPU Info

Show output of:

+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 550.54.15              Driver Version: 550.54.15      CUDA Version: 12.4     |
|-----------------------------------------+------------------------+----------------------+
| GPU  Name                 Persistence-M | Bus-Id          Disp.A | Volatile Uncorr. ECC |
| Fan  Temp   Perf          Pwr:Usage/Cap |           Memory-Usage | GPU-Util  Compute M. |
|                                         |                        |               MIG M. |
|=========================================+========================+======================|
|   0  Tesla T4                       Off |   00000000:00:04.0 Off |                    0 |
| N/A   72C    P0             35W /   70W |     326MiB /  15360MiB |     19%      Default |
|                                         |                        |                  N/A |
+-----------------------------------------+------------------------+----------------------+
                                                                                         
+-----------------------------------------------------------------------------------------+
| Processes:                                                                              |
|  GPU   GI   CI        PID   Type   Process name                              GPU Memory |
|        ID   ID                                                               Usage      |
|=========================================================================================|
+-----------------------------------------------------------------------------------------+

Software Info

Operating System: Linux #1 SMP PREEMPT_DYNAMIC Thu Jun 27 21:05:47 UTC 2024 Python Version: 3.11.11

Name: gptqmodel
Version: 2.1.1.dev0
Summary: Production ready LLM model compression/quantization toolkit with hw accelerated inference support for both cpu/gpu via HF, vLLM, and SGLang.
Home-page: https://github.com/ModelCloud/GPTQModel
Author: ModelCloud
Author-email: [[email protected]](mailto:[email protected])
License: Apache 2.0
Location: /usr/local/lib/python3.11/dist-packages
Requires: accelerate, datasets, device-smi, hf-transfer, huggingface-hub, logbar, numpy, packaging, pillow, protobuf, random-word, safetensors, threadpoolctl, tokenicer, torch, transformers
Required-by: 
---
Name: torch
Version: 2.6.0+cu124
Summary: Tensors and Dynamic neural networks in Python with strong GPU acceleration
Home-page: https://pytorch.org/
Author: PyTorch Team
Author-email: [[email protected]](mailto:[email protected])
License: BSD-3-Clause
Location: /usr/local/lib/python3.11/dist-packages
Requires: filelock, fsspec, jinja2, networkx, nvidia-cublas-cu12, nvidia-cuda-cupti-cu12, nvidia-cuda-nvrtc-cu12, nvidia-cuda-runtime-cu12, nvidia-cudnn-cu12, nvidia-cufft-cu12, nvidia-curand-cu12, nvidia-cusolver-cu12, nvidia-cusparse-cu12, nvidia-cusparselt-cu12, nvidia-nccl-cu12, nvidia-nvjitlink-cu12, nvidia-nvtx-cu12, sympy, triton, typing-extensions
Required-by: accelerate, fastai, gptqmodel, peft, sentence-transformers, timm, torchaudio, torchvision
---
Name: transformers
Version: 4.50.0
Summary: State-of-the-art Machine Learning for JAX, PyTorch and TensorFlow
Home-page: https://github.com/huggingface/transformers
Author: The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)
Author-email: [[email protected]](mailto:[email protected])
License: Apache 2.0 License
Location: /usr/local/lib/python3.11/dist-packages
Requires: filelock, huggingface-hub, numpy, packaging, pyyaml, regex, requests, safetensors, tokenizers, tqdm
Required-by: gptqmodel, peft, sentence-transformers, tokenicer
---
Name: accelerate
Version: 1.5.2
Summary: Accelerate
Home-page: https://github.com/huggingface/accelerate
Author: The HuggingFace team
Author-email: [[email protected]](mailto:[email protected])
License: Apache
Location: /usr/local/lib/python3.11/dist-packages
Requires: huggingface-hub, numpy, packaging, psutil, pyyaml, safetensors, torch
Required-by: gptqmodel, peft
---
Name: triton
Version: 3.2.0
Summary: A language and compiler for custom Deep Learning operations
Home-page: https://github.com/triton-lang/triton/
Author: Philippe Tillet
Author-email: [[email protected]](mailto:[email protected])
License: 
Location: /usr/local/lib/python3.11/dist-packages
Requires: 
Required-by: torch

config.json:

{
  "_remove_final_layer_norm": false,
  "activation_dropout": 0.0,
  "activation_function": "relu",
  "architectures": [
    "OPTForCausalLM"
  ],
  "attention_dropout": 0.0,
  "bos_token_id": 2,
  "do_layer_norm_before": true,
  "dropout": 0.1,
  "enable_bias": true,
  "eos_token_id": 2,
  "ffn_dim": 3072,
  "hidden_size": 768,
  "init_std": 0.02,
  "layer_norm_elementwise_affine": true,
  "layerdrop": 0.0,
  "max_position_embeddings": 2048,
  "model_type": "opt",
  "num_attention_heads": 12,
  "num_hidden_layers": 12,
  "pad_token_id": 1,
  "prefix": "</s>",
  "quantization_config": {
    "bits": 4,
    "checkpoint_format": "gptq",
    "desc_act": true,
    "group_size": 128,
    "lm_head": false,
    "meta": {
      "damp_auto_increment": 0.0025,
      "damp_percent": 0.01,
      "mse": 0.0,
      "quantizer": [
        "gptqmodel:2.1.1-dev"
      ],
      "static_groups": false,
      "true_sequential": true,
      "uri": "https://github.com/modelcloud/gptqmodel"
    },
    "pack_dtype": "int32",
    "quant_method": "gptq",
    "sym": true
  },
  "torch_dtype": "float16",
  "transformers_version": "4.50.0",
  "use_cache": true,
  "vocab_size": 50272,
  "word_embed_proj_dim": 768
}

quantize_config.json

{
  "bits": 4,
  "group_size": 128,
  "desc_act": true,
  "sym": true,
  "lm_head": false,
  "quant_method": "gptq",
  "checkpoint_format": "gptq",
  "pack_dtype": "int32",
  "meta": {
    "quantizer": [
      "gptqmodel:2.1.1-dev"
    ],
    "uri": "https://github.com/modelcloud/gptqmodel",
    "damp_percent": 0.01,
    "damp_auto_increment": 0.0025,
    "static_groups": false,
    "true_sequential": true,
    "mse": 0.0
  }
}

To Reproduce

Quantize the model and run it, using the code from readme.md:

from datasets import load_dataset
from gptqmodel import GPTQModel, QuantizeConfig

model_id = "facebook/opt-125m"
quant_path = "opt-125m-GPTQ-4bit-g128"

calibration_dataset = load_dataset(
    "allenai/c4",
    data_files="en/c4-train.00001-of-01024.json.gz",
    split="train"
  ).select(range(2048))["text"]
calibration_dataset=['\n'.join(i.split('\n')[:3]) for i in calibration_dataset]
# filter long contexts for small models so that they fit in n_tokens limit

quant_config = QuantizeConfig(bits=4, group_size=128)

model = GPTQModel.load(model_id, quant_config)
# increase `batch_size` to match gpu/vram specs to speed up quantization
model.quantize(calibration_dataset, batch_size=2)

model.save(quant_path)

# test post-quant inference
model = GPTQModel.load(quant_path)
result = model.generate("Uncovering deep insights")[0] # tokens
print(model.tokenizer.decode(result)) # string output

Generation produced by the model: </s>Uncovering deep insights,,,,,,,,,,,,,,,,,,,,

Expected behavior

The model generates some text.

Model/Datasets

The calibration dataset C4 is available on hf.

Additional info
I experienced the same when using the GPTQModel class for the models quantized with auto-gptq, such as iproskurina/opt-125m-GPTQ-4bit-g128

Activity

  1. added
    bug
    on Mar 27, 2025
  2. changed the title [-][BUG] Model Load[/-] [+][BUG] OPT-125m not working after quantization [/+] on Mar 27, 2025
  3. Qubitium commented on Mar 28, 2025

    @Qubitium
    Collaborator

    @upunaprosk Ok. Let's try to isolate. Can you use HF to load the quant iproskurina/opt-125m-GPTQ-4bit-g128 and check if output is same? I want to make sure this is not a HF regression for OPT

    model = AutoModelForCasual("iproskurina/opt-125m-GPTQ-4bit-g128")
  4. upunaprosk commented on Mar 29, 2025

    @upunaprosk
    Author

    Both models (quantized with gptqmodel and auto-gptq) don't work with AutoModelForCausalLM (Transformers 4.50.0), regardless of decoding strategy and optimum version that it requires.

    However, .generate works fine with GPTQModel using gptqmodel ≤2.0.0.
    I’m not sure why it doesn't work for the latest version, as there are no version conflicts.
    Since using gptqmodel ≤2.0.0 solves it, the issue can be closed.

  5. BUGBOY101 commented on Mar 30, 2025

    @BUGBOY101

    Hello, @upunaprosk. I would like to ask if you can load the model quantized with gptqmodel using AutoModelForCausalLM. I encountered an error when testing with model = AutoModelForCausalLM.from_pretrained(model_id_or_path):

    Full code for loading the model:

        # Load the base model and tokenizer (unchanged)
        model_path = args.model_path  # Get the base model path from command-line arguments
        adapter_path = args.adapter_path  # Get the fine-tuned adapter path from command-line arguments
        tokenizer = AutoTokenizer.from_pretrained(model_path, cache_dir='../cache')  # Replace with your cache path
        gpu_id = args.gpu
        free_in_GB = 32  # Adjust according to the actual VRAM of your GPU 2
        max_memory = {gpu_id: f"{free_in_GB}GB"}  # Set memory only for GPU 2
    
        model = AutoModelForCausalLM.from_pretrained(
            model_path,
            device_map='cuda:{}'.format(gpu_id),  # Directly specify loading to cuda:2
            max_memory=max_memory,
            cache_dir='../cache',
            torch_dtype=torch.float16,
            low_cpu_mem_usage=True
        )

    Error message:
    File "/root/data1/bjtu_wzx/zyq/fine_tuning/Simple_running/test/cot_generate.py", line 276, in <module> main(args) File "/root/data1/bjtu_wzx/zyq/fine_tuning/Simple_running/test/cot_generate.py", line 139, in main model = AutoModelForCausalLM.from_pretrained( File "/root/miniconda3/envs/llama/lib/python3.10/site-packages/transformers/models/auto/auto_factory.py", line 573, in from_pretrained return model_class.from_pretrained( File "/root/miniconda3/envs/llama/lib/python3.10/site-packages/transformers/modeling_utils.py", line 272, in _wrapper return func(*args, **kwargs) File "/root/miniconda3/envs/llama/lib/python3.10/site-packages/transformers/modeling_utils.py", line 4455, in from_pretrained ) = cls._load_pretrained_model( File "/root/miniconda3/envs/llama/lib/python3.10/site-packages/transformers/modeling_utils.py", line 4884, in _load_pretrained_model disk_offload_index, cpu_offload_index = _load_state_dict_into_meta_model( File "/root/miniconda3/envs/llama/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context return func(*args, **kwargs) File "/root/miniconda3/envs/llama/lib/python3.10/site-packages/transformers/modeling_utils.py", line 852, in _load_state_dict_into_meta_model {param_type: param.to(param_device)}, RuntimeError: CUDA error: invalid device ordinal CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect. For debugging consider passing CUDA_LAUNCH_BLOCKING=1 Compile withTORCH_USE_CUDA_DSA to enable device-side assertions.

  6. Qubitium commented on Mar 31, 2025

    @Qubitium
    Collaborator

    @BUGBOY101 Please stop using AI to generate your code. Read our readme on dead simple loading code.

  7. Qubitium commented on Apr 2, 2025

    @Qubitium
    Collaborator

    @upunaprosk I am not sure but it looks like OPT support in latest versions of transformers is broken?

      File "/root/GPTQModel/gptqmodel/models/base.py", line 450, in quantize
        return module_looper.loop(
               ^^^^^^^^^^^^^^^^^^^
      File "/root/vm312/lib/python3.12/site-packages/torch/utils/_contextlib.py", line 116, in decorate_context
        return func(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^
      File "/root/GPTQModel/gptqmodel/looper/module_looper.py", line 171, in loop
        input_cache = self.cache_inputs(layers=layers, auto_gc=auto_gc,
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/root/GPTQModel/gptqmodel/looper/module_looper.py", line 114, in cache_inputs
        self.gptq_model.model(**example)
      File "/root/vm312/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1739, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/root/vm312/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1750, in _call_impl
        return forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/root/vm312/lib/python3.12/site-packages/transformers/models/opt/modeling_opt.py", line 1194, in forward
        outputs = self.model.decoder(
                  ^^^^^^^^^^^^^^^^^^^
      File "/root/vm312/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1739, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/root/vm312/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1750, in _call_impl
        return forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/root/vm312/lib/python3.12/site-packages/transformers/models/opt/modeling_opt.py", line 895, in forward
        pos_embeds = self.embed_positions(attention_mask, past_seen_tokens, position_ids=position_ids)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/root/vm312/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1739, in _wrapped_call_impl
        return self._call_impl(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/root/vm312/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1750, in _call_impl
        return forward_call(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/root/vm312/lib/python3.12/site-packages/transformers/models/opt/modeling_opt.py", line 99, in forward
        return super().forward(position_ids + self.offset)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "/root/vm312/lib/python3.12/site-packages/torch/nn/modules/sparse.py", line 190, in forward
        return F.embedding(
               ^^^^^^^^^^^^
      File "/root/vm312/lib/python3.12/site-packages/torch/nn/functional.py", line 2551, in embedding
        return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    IndexError: index out of range in self
  8. upunaprosk commented on Apr 3, 2025

    @upunaprosk
    Author

    @Qubitium Yes, I have the same error with the latest version 4.50.0

  9. simlang commented on Apr 9, 2025

    @simlang

    Ran into the same issue on the same model, switching from a Tesla T4 to an A10 resolved the problem. Might be related to the GPU?

  10. Qubitium commented on Apr 9, 2025

    @Qubitium
    Collaborator

    @simlang I have no idea. I just tested on GPTQModel main with latest transformers 4.51.1 and opt is working again. I am using our tests/models/test_opt.py to test quant and post quant inference.

  11. simlang commented on Apr 9, 2025

    @simlang

    @Qubitium Did you try this on a T4?

  12. Qubitium commented on Apr 9, 2025

    @Qubitium
    Collaborator

    @simlang No. on a A100. GPTQ algorithm requires accurate fp32 math. Maybe T4 has bad or substandard fp32 accuracy vs later chips/A100? I see accuracy issue between 4090 and A100 so maybe the lower (guessing here) accuracy issues of the T4 is causing bad quantization alignment/calibration.

  13. Qubitium commented on Apr 13, 2025

    @Qubitium
    Collaborator

    Guys, I am closing this issue for now until we get more information on exactly what's wrong with T4 and OPT. Right now our test_opt.py in tests/model is passing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions