Repository: huggingface/transformers
Pull request: remove torchao.autoquant from transformers

Summary:

This is being deprecated: https://github.com/pytorch/ao/issues/3739

Test Plan:

```python
RUN_SLOW=1 pytest tests/quantization/torchao_integration/test_torchao.py -s
```

# What does this PR do?

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes # (issue)


## Before submitting
- [x] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [x] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [x] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?


## Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker @Cyrilvallez
- vision models: @yonigozlan @molbap
- audio models: @eustlb @ebezzam @vasqu
- multimodal models: @zucchini-nlp
- graph models: @clefourrier

Library:

- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- continuous batching: @remi-or @ArthurZucker @McPatate
- pipelines: @Rocketknight1
- tokenizers: @ArthurZucker and @itazap
- trainer: @SunMarc
- attention: @vasqu @ArthurZucker @CyrilVallez
- model loading (from pretrained, etc): @CyrilVallez
- distributed: @3outeille @ArthurZucker
- CIs: @ydshieh

Integrations:

- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization: @SunMarc @MekkCyber
- kernels: @MekkCyber @drbh
- peft: @BenjaminBossan @githubnemo

Devices/Backends:

- AMD ROCm: @ivarflakstad
- Intel XPU: @IlyasMoutawwakil
- Ascend NPU: @ivarflakstad 

Documentation: @stevhliu

Research projects are not maintained and should be taken as is.

 -->


Changed files:
filename: docs/source/en/quantization/torchao.md
patch: @@ -605,39 +605,6 @@ print("Response:", output_text[0][len(prompt) :])
 assert(correct_output_text == output_text)
 ```
 
-### Autoquant
-
-If you want to automatically choose a quantization type for quantizable layers (`nn.Linear`) you can use the [autoquant](https://pytorch.org/ao/stable/generated/torchao.quantization.autoquant.html#torchao.quantization.autoquant) API.
-
-The `autoquant` API automatically chooses a quantization type by micro-benchmarking on input type and shape and compiling a single linear layer.
-
-Note: autoquant is for GPU only right now.
-
-Create a [`TorchAoConfig`] and set to `"autoquant"`. Set the `cache_implementation` to `"static"` to automatically [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) the forward method. Finally, call `finalize_autoquant` on the quantized model to finalize the quantization and log the input shapes.
-
-```py
-import torch
-from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
-
-quantization_config = TorchAoConfig("autoquant", min_sqnr=None)
-quantized_model = AutoModelForCausalLM.from_pretrained(
-    "meta-llama/Llama-3.1-8B-Instruct",
-    dtype="auto",
-    device_map="auto",
-    quantization_config=quantization_config
-)
-
-tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
-input_text = "What are we having for dinner?"
-input_ids = tokenizer(input_text, return_tensors="pt").to(quantized_model.device.type)
-
-# auto-compile the quantized model with `cache_implementation="static"` to get speed up
-output = quantized_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static")
-# explicitly call `finalize_autoquant` (may be refactored and removed in the future)
-quantized_model.finalize_autoquant()
-print(tokenizer.decode(output[0], skip_special_tokens=True))
-```
-
 ## Serialization
 
 Saving the quantized model with `save_pretrained` (in [safetensors](https://huggingface.co/docs/safetensors/en/index) format) is only supported for torchao >= v0.15. For any version below, it is only possible to manually save as unsafe `.bin` checkpoints with [torch.save](https://docs.pytorch.org/docs/stable/generated/torch.save.html).

filename: src/transformers/quantizers/quantizer_torchao.py
patch: @@ -181,9 +181,6 @@ def _process_model_before_weight_loading(self, model: "PreTrainedModel", checkpo
             self.set_metadata(checkpoint_files)
 
     def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
-        if self.quantization_config.quant_type == "autoquant":
-            return False
-
         # check if the param_name is not in self.modules_to_not_convert
         if not should_convert_module(param_name, self.modules_to_not_convert):
             return False
@@ -213,19 +210,6 @@ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **
         return isinstance(module, tuple(_QUANTIZABLE)) and tensor_name == "weight"
 
     def _process_model_after_weight_loading(self, model, **kwargs):
-        """No process required for torchao quantized model"""
-        if self.quantization_config.quant_type == "autoquant":
-            from torchao import autoquant
-            from torchao.quantization import ALL_AUTOQUANT_CLASS_LIST
-
-            model = torch.compile(model, mode="max-autotune")
-            model = autoquant(
-                model,
-                qtensor_class_list=ALL_AUTOQUANT_CLASS_LIST,
-                set_inductor_config=False,
-                **self.quantization_config.quant_type_kwargs,
-            )
-            return model
         return
 
     def is_serializable(self) -> bool:

filename: src/transformers/utils/quantization_config.py
patch: @@ -1488,25 +1488,6 @@ class TorchAoConfig(QuantizationConfigMixin):
     # int4_weight_only quant is only working with *torch.bfloat16* dtype right now
     model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", dtype=torch.bfloat16, quantization_config=quantization_config)
 
-    # autoquant
-    # `autoquant` is a convenient way for users to search for the best quantization for each layer
-    # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more
-    # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)
-    # defaults to None, which means we'll try to get the best performing quantized model without
-    # considering accuracy
-    quantization_config = TorchAoConfig("autoquant", min_sqnr=30)
-    model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda", dtype=torch.bfloat16, quantization_config=quantization_config)
-    # run through example inputs, quantization methods will be selected based on the shape of example input
-    tokenizer = AutoTokenizer.from_pretrained(model_name)
-    input_text = "What are we having for dinner?"
-    input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
-    MAX_NEW_TOKENS = 1000
-    model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation="static")
-    # manually ran finalize_autoquant if needed
-    if hasattr(quantized_model, "finalize_autoquant"):
-      print("finalizing autoquant")
-      quantized_model.finalize_autoquant()
-
     ```
     """
 
@@ -1583,7 +1564,6 @@ def _validate_string_quant_type(self):
     def _get_torchao_quant_type_to_method(self):
         """Get mapping of quant_type strings to their corresponding methods."""
         from torchao.quantization import (
-            autoquant,
             int4_weight_only,
             int8_dynamic_activation_int8_weight,
             int8_weight_only,
@@ -1593,7 +1573,6 @@ def _get_torchao_quant_type_to_method(self):
             "int4_weight_only": int4_weight_only,
             "int8_weight_only": int8_weight_only,
             "int8_dynamic_activation_int8_weight": int8_dynamic_activation_int8_weight,
-            "autoquant": autoquant,
         }
 
     def get_apply_tensor_subclass(self):

filename: tests/quantization/torchao_integration/test_torchao.py
patch: @@ -57,7 +57,6 @@
         ModuleFqnToConfig,
         PerAxis,
     )
-    from torchao.quantization.autoquant import AQMixin
 
     if version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0"):
         from torchao.dtypes import Int4CPULayout
@@ -82,11 +81,6 @@ def check_torchao_int4_wo_quantized(test_module, qlayer):
     test_module.assertTrue(isinstance(weight.tensor_impl._layout, layout))
 
 
-def check_autoquantized(test_module, qlayer):
-    weight = qlayer.weight
-    test_module.assertTrue(isinstance(weight, AQMixin))
-
-
 def check_forward(test_module, model, batch_size=1, context_size=1024):
     # Test forward pass
     with torch.no_grad():
@@ -699,34 +693,6 @@ def test_int4wo_quant_multi_accelerator(self):
         output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens)
         self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
 
-    def test_autoquant(self):
-        """
-        Simple LLM model testing autoquant
-        """
-        quant_config = TorchAoConfig("autoquant")
-
-        quantized_model = AutoModelForCausalLM.from_pretrained(
-            self.model_name,
-            torch_dtype="auto",
-            device_map=self.device,
-            quantization_config=quant_config,
-        )
-        tokenizer = AutoTokenizer.from_pretrained(self.model_name)
-        input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device)
-        output = quantized_model.generate(
-            **input_ids, max_new_tokens=self.max_new_tokens, cache_implementation="static"
-        )
-        quantized_model.finalize_autoquant()
-
-        check_autoquantized(self, quantized_model.model.layers[0].self_attn.v_proj)
-
-        EXPECTED_OUTPUTS = ["What are we having for dinner?\n\nJessica: (smiling)", "What are we having for dinner?"]
-
-        output = quantized_model.generate(
-            **input_ids, max_new_tokens=self.max_new_tokens, cache_implementation="static"
-        )
-        self.assertIn(tokenizer.decode(output[0], skip_special_tokens=True), EXPECTED_OUTPUTS)
-
 
 @require_torchao_version_greater_or_equal("0.15.0")
 @slow