AQLM quantizer support
Author: BlackSamorez
Pull request: yes

# 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 https://github.com/Vahe1994/AQLM/issues/11


## Before submitting
- [ ] 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#start-contributing-pull-requests),
      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).
- [x] 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.

@younesbelkada

<!-- 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 and @younesbelkada
- vision models: @amyeroberts
- speech models: @sanchit-gandhi
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @gante
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @pacman100

Integrations:

- deepspeed: HF Trainer/Accelerate: @pacman100
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc and @younesbelkada

Documentation: @stevhliu and @MKhalusova

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: @sanchit-gandhi
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
A model to test it: [BlackSamorez/Mixtral-8x7b-AQLM-2Bit-1x16-hf-test-dispatch](https://huggingface.co/BlackSamorez/Mixtral-8x7b-AQLM-2Bit-1x16-hf-test-dispatch)

A Google Colab demo: [Mixtral in 2 bits](https://colab.research.google.com/drive/1-xZmBRXT5Fm3Ghn4Mwa2KRypORXb855X?usp=sharing).

The docs for this PR live [here](https://moon-ci-docs.huggingface.co/docs/transformers/pr_28928). All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

cc @oobabooga this might be of your interest ! 

I updated the docked recipe and added tests, but they are skipped because `aqlm` is not installed in the testing environment.

The tests are still getting skipped. Is putting `aqlm` in the dockerfile enough for the testing environment to get it?

I'm pretty sure tests failing has nothing to do with my PR

@BlackSamorez on a google colab env the inference script works great, however on my VM, on a python 3.10 env with latest torch + cuda11.8 I constantly get:
```bash
Traceback (most recent call last):
  File "/transformers/scratch.py", line 11, in <module>
    output = quantized_model.generate(tokenizer("", return_tensors="pt")["input_ids"].cuda(), max_new_tokens=10)
  File "/miniconda3/envs/aqlm/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
    return func(*args, **kwargs)
  File "/transformers/src/transformers/generation/utils.py", line 1495, in generate
    return self.greedy_search(
  File "/transformers/src/transformers/generation/utils.py", line 2366, in greedy_search
    next_tokens = torch.argmax(next_tokens_scores, dim=-1)
RuntimeError: CUDA error: device kernel image is invalid
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.
```
Do you have an idea what might be wrong here?

The only difference I see between the colab instance and mine is the CUDA version, I'll update it to 12.1 and loop back here

@younesbelkada 
The kernel is compiled in runtime with 
```python
import os
from typing import Optional

import torch
from torch.utils.cpp_extension import load

CUDA_FOLDER = os.path.dirname(os.path.abspath(__file__))
CUDA_KERNEL = load(
    name="codebook_cuda",
    sources=[os.path.join(CUDA_FOLDER, "cuda_kernel.cpp"), os.path.join(CUDA_FOLDER, "cuda_kernel.cu")],
)
```

Maybe your `nvcc` is sourced from an incorrect cuda installment. I'm not really sure how to test it. Maybe you could try specifying an `nvcc` path somehow with an environmental variable.
I'll try to reproduce it as well.

CUDA 11.8 seems to work fine on my machine on an a100 GPU.

FYI: I've released `aqlm` version `1.0.1` where I added device guards to fix CUDA errors when running in the multi-gpu setup. I've added the corresponding tests similar to `autoawq` ones

Looks like some network error occured 

🤗 🚀 

Hi @BlackSamorez ! 
Thanks again for your great work ! I was wondering if you could update the installation cell on the shared notebook to install transformers from source instead of your fork - that way we could catch potential bugs in the future before the release 🙏 

@younesbelkada 
Looks like [this commit](https://github.com/huggingface/transformers/commit/164bdef8cc5143a0766cee448e97166682a722b1) outside of the PR broke something.
```python
AttributeError                            Traceback (most recent call last)

[<ipython-input-2-68b1b199d504>](https://localhost:8080/#) in <cell line: 3>()
      1 from transformers import AutoTokenizer, AutoModelForCausalLM
      2 
----> 3 quantized_model = AutoModelForCausalLM.from_pretrained(
      4     "BlackSamorez/Mixtral-8x7b-AQLM-2Bit-1x16-hf-test-dispatch",
      5     torch_dtype="auto", device_map="auto", low_cpu_mem_usage=True,

4 frames

[/usr/local/lib/python3.10/dist-packages/transformers/models/auto/auto_factory.py](https://localhost:8080/#) in from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs)
    565         elif type(config) in cls._model_mapping.keys():
    566             model_class = _get_model_class(config, cls._model_mapping)
--> 567             return model_class.from_pretrained(
    568                 pretrained_model_name_or_path, *model_args, config=config, **hub_kwargs, **kwargs
    569             )

[/usr/local/lib/python3.10/dist-packages/transformers/modeling_utils.py](https://localhost:8080/#) in from_pretrained(cls, pretrained_model_name_or_path, config, cache_dir, ignore_mismatched_sizes, force_download, local_files_only, token, revision, use_safetensors, *model_args, **kwargs)
   3561 
   3562         if hf_quantizer is not None:
-> 3563             hf_quantizer.postprocess_model(model)
   3564             model.hf_quantizer = hf_quantizer
   3565 

[/usr/local/lib/python3.10/dist-packages/transformers/quantizers/base.py](https://localhost:8080/#) in postprocess_model(self, model, **kwargs)
    177                 The keyword arguments that are passed along `_process_model_after_weight_loading`.
    178         """
--> 179         return self._process_model_after_weight_loading(model, **kwargs)
    180 
    181     @abstractmethod

[/usr/local/lib/python3.10/dist-packages/transformers/quantizers/quantizer_aqlm.py](https://localhost:8080/#) in _process_model_after_weight_loading(self, model, **kwargs)
     78 
     79     def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
---> 80         model._is_quantized_training_enabled = False
     81         return model
     82 

[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in __setattr__(self, name, value)
   1745                     buffers[name] = value
   1746                 else:
-> 1747                     super().__setattr__(name, value)
   1748 
   1749     def __delattr__(self, name):

AttributeError: can't set attribute '_is_quantized_training_enabled'
```