Repository: huggingface/transformers
Pull request: Allow compression on meta device

# What does this PR do?
This PR depends on compressed-tensor updates [here](https://github.com/neuralmagic/compressed-tensors/pull/376/files) that allows compression on meta device.

<!--
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 -->
In `_process_model_before_weight_loading`, always compress meta device model when the checkpoint model is quantized/sparsified. 

In `_process_model_after_weight_loading`, just decompress if needed.

Rationale
Fixes runtime errors like:
```
Only Tensors of floating point and complex dtype can require gradients
```
Ensures proper behavior when loading and using compressed models.


Fixes # (issue)


## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] 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.
- [ ] 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
- vision models: @amyeroberts, @qubvel
- speech models: @eustlb
- graph models: @clefourrier

Library:

- flax: @gante and @Rocketknight1
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Rocketknight1
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @zach-huggingface, @SunMarc and @qgallouedec
- chat templates: @Rocketknight1

Integrations:

- deepspeed: HF Trainer/Accelerate: @SunMarc @zach-huggingface
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc @MekkCyber

Documentation: @stevhliu

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @Rocketknight1
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Changed files:
filename: src/transformers/quantizers/quantizer_compressed_tensors.py
patch: @@ -13,9 +13,6 @@
 # limitations under the License.
 
 
-import os
-import re
-
 from ..utils import is_compressed_tensors_available, is_torch_available, logging
 from ..utils.quantization_config import CompressedTensorsConfig
 from .base import HfQuantizer
@@ -55,45 +52,6 @@ def __init__(self, quantization_config: CompressedTensorsConfig, **kwargs):
         self.run_compressed = quantization_config.run_compressed
         self.quantization_config = quantization_config
 
-    def update_missing_keys_after_loading(self, model, missing_keys: list[str], prefix: str) -> list[str]:
-        """
-        Update missing keys after loading the model. This is necessary for compressed tensors
-        to load the model correctly. We expect weights to be present in missing keys.
-        The weight's are re-constructed by ModelCompressor in _process_model_after_weight_loading
-
-        This function cleans up expected missing keys and returns the remaining missing keys
-        """
-
-        if self.run_compressed:
-            return missing_keys
-
-        # We expect some keys to be missing for
-        # compressed models
-        # This is fine as the weights are reconstructed by ModelCompressor
-        # in _process_model_after_weight_loading
-
-        expected_missing_keys = self.compressor.get_missing_module_keys(model)
-        return [
-            key for key in missing_keys if not any(re.match(f".*{pattern}", key) for pattern in expected_missing_keys)
-        ]
-
-    def update_unexpected_keys(self, model, unexpected_keys: list[str], prefix: str) -> list[str]:
-        """
-        Override this method if you want to adjust the `unexpected_keys`.
-
-        Args:
-            unexpected_keys (`list[str]`, *optional*):
-                The list of unexpected keys in the checkpoint compared to the state dict of the model
-        """
-
-        if self.run_compressed:
-            return unexpected_keys
-
-        # We expect some unexpected keys in model
-        # safetensors file for compressed models
-        keys_to_ignore = self.compressor.get_unexpected_file_keys(model)
-        return [key for key in unexpected_keys if not any(re.match(f".*{pattern}", key) for pattern in keys_to_ignore)]
-
     def validate_environment(self, *args, **kwargs):
         if not is_compressed_tensors_available():
             raise ImportError(
@@ -117,31 +75,21 @@ def _process_model_before_weight_loading(self, model, **kwargs):
 
         ct_quantization_config = self.compressor.quantization_config
 
-        if self.run_compressed:
-            apply_quantization_config(model, ct_quantization_config, run_compressed=True)
-        elif not self.quantization_config.is_quantization_compressed:
-            apply_quantization_config(model, ct_quantization_config)
+        # Always initialize compressed wrappers to match the checkpoint
+        apply_quantization_config(model, ct_quantization_config, self.run_compressed)
+        if (
+            self.quantization_config.is_quantization_compressed
+            or self.quantization_config.is_sparsification_compressed
+        ):
+            self.compressor.compress_model(model=model)
 
     def _process_model_after_weight_loading(self, model, **kwargs):
         """Decompress loaded model if necessary - need for qat"""
 
         if (
             self.quantization_config.is_quantization_compressed and not self.run_compressed
         ) or self.quantization_config.is_sparsification_compressed:
-            config = kwargs.get("config")
-            cache_path = config._name_or_path
-
-            if not os.path.exists(cache_path):
-                from transformers.utils import cached_file
-
-                config_file_path = cached_file(cache_path, "config.json")
-                cache_path = os.path.sep.join(config_file_path.split(os.path.sep)[:-1])
-
-            if self.quantization_config.is_quantization_compressed and not self.run_compressed:
-                from compressed_tensors.quantization import QuantizationStatus
-
-                self.compressor.quantization_config.quantization_status = QuantizationStatus.FROZEN
-            self.compressor.decompress(model_path=cache_path, model=model)
+            self.compressor.decompress_model(model=model)
 
     def update_tp_plan(self, config):
         additional_plan = {