跳到内容

TorchAO

TorchAO 是一个用于 PyTorch 的架构优化库,它提供了高性能的数据类型(dtypes)、优化技术和内核,用于推理和训练。它具备与原生 PyTorch 功能(如 torch.compile、FSDP 等)的组合性。一些基准测试数据可以在这里找到。

我们建议通过以下命令安装最新的 torchao nightly 版本:

# Install the latest TorchAO nightly build
# Choose the CUDA version that matches your system (cu126, cu128, etc.)
pip install \
    --pre torchao>=10.0.0 \
    --index-url https://download.pytorch.org/whl/nightly/cu126

量化 HuggingFace 模型

你可以使用 torchao 量化你自己的 HuggingFace 模型,例如通过 transformersdiffusers,并参考此示例,通过下方的代码示例将检查点(checkpoint)保存到 HuggingFace Hub。

代码
import torch
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
from torchao.quantization import Int8WeightOnlyConfig

model_name = "meta-llama/Meta-Llama-3-8B"
quantization_config = TorchAoConfig(Int8WeightOnlyConfig())
quantized_model = AutoModelForCausalLM.from_pretrained(
    model_name,
    dtype="auto",
    device_map="auto",
    quantization_config=quantization_config
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
input_text = "What are we having for dinner?"
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")

hub_repo = # YOUR HUB REPO ID
tokenizer.push_to_hub(hub_repo)
quantized_model.push_to_hub(hub_repo, safe_serialization=False)

此外,你也可以使用 TorchAO 量化空间,通过简单的用户界面对模型进行量化。