# HQQ

[Half-Quadratic Quantization (HQQ)](https://github.com/mobiusml/hqq/)は、8、4、3、2、さらには1ビットでの高速なオンザフライ量子化をサポートしています。キャリブレーションデータは不要であり、あらゆるモデルのモダリティ（LLM、ビジョンなど）と互換性があります。

HQQはさらに[PEFT](https://huggingface.co/docs/peft)によるファインチューニングをサポートしており、[torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html)と完全に互換性があるため、より高速な推論とトレーニングを実現できます。

pip install hqq

```bash
pip install hqq
```

モデル内のすべての線形層を同じ量子化設定に置き換えるか、特定の線形層に特定の量子化設定を割り当てるかを選択できます。

[HqqConfig](/docs/transformers/main/ja/main_classes/quantization#transformers.HqqConfig) を作成し、`nbits` と `group_size` を指定して、モデルのすべての線形層（[torch.nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html)）を置き換えることで、モデルを量子化します。

``` py
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, HqqConfig

quant_config = HqqConfig(nbits=8, group_size=64)
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B", 
    dtype=torch.float16, 
    device_map="auto", 
    quantization_config=quant_config
)
```

Quantize a model by creating a dictionary specifying the `nbits` and `group_size` for the linear layers to quantize. Pass them to [HqqConfig](/docs/transformers/main/ja/main_classes/quantization#transformers.HqqConfig) and set which layers to quantize with the config. This approach is especially useful for quantizing mixture-of-experts (MoEs) because they are less affected ly lower quantization settings.

``` py
q4_config = {'nbits':4, 'group_size':64}
q3_config = {'nbits':3, 'group_size':32}
quant_config  = HqqConfig(dynamic_config={
  'self_attn.q_proj':q4_config,
  'self_attn.k_proj':q4_config,
  'self_attn.v_proj':q4_config,
  'self_attn.o_proj':q4_config,

  'mlp.gate_proj':q3_config,
  'mlp.up_proj'  :q3_config,
  'mlp.down_proj':q3_config,
})

model = transformers.AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B", 
    dtype=torch.float16, 
    device_map="auto", 
    quantization_config=quant_config
)
```

## バックエンド

HQQは、純粋なPyTorchやカスタムdequantization CUDAカーネルなど、さまざまなバックエンドをサポートしています。これらのバックエンドは、古いGPUやPEFT/QLoRAのトレーニングに適しています。

```py
from hqq.core.quantize import *

HQQLinear.set_backend(HQQBackend.PYTORCH)
```

より高速な推論のために、HQQ はモデルの量子化後に 4-bit 融合カーネル（torchao および Marlin）をサポートしています。これにより、単一の 4090 で最大 200 tokens/sec に達することが可能です。以下の例では、torchao_int4 バックエンドを有効にする方法を示しています。

```py
from hqq.utils.patching import prepare_for_inference

prepare_for_inference("model", backend="torchao_int4")
```

詳細については、[Backend](https://github.com/mobiusml/hqq/#backend)ガイドを参照してください。

## リソース

HQQの詳細については、[大規模機械学習モデルの半二次量子化](https://mobiusml.github.io/hqq_blog/)というブログ記事をお読みください。

