PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
# Copyright (c) 2024 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import sys
from collections import OrderedDict
from inspect import signature
from typing import Any
import torch
from torch.utils.data import DataLoader, Dataset
from transformers import set_seed
from auto_round.logger import logger
from auto_round.special_model_handler import check_mllm_only_support_bs1
from .template import Template
from .utils import _extract_data_dir
MLLM_DATASET: dict[str, Dataset] = {}
def register_dataset(name_list):
"""Class decorator to register a DATASET subclass to the registry.
Decorator function used before a Pattern subclass.
Args:
name: A string. Define the dataset type.
Returns:
cls: The class of register.
"""
def register(dataset):
for name in name_list.replace(" ", "").split(","):
MLLM_DATASET[name] = dataset
return register
@register_dataset(
"liuhaotian/llava,liuhaotian/llava_conv_58k,liuhaotian/llava_instruct_80k,liuhaotian/llava_instruct_150k"
)
class LlavaDataset(Dataset):
"""Dataset for supervised fine-tuning."""
LLAVA_REPO_ID = "liuhaotian/LLaVA-Instruct-150K"
BASE_LLAVA_URL = "https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K/resolve/main/"
LLAVA_DATASET_FILES = {
"llava_conv_58k": "conversation_58k.json",
"llava_instruct_80k": "llava_instruct_80k.json",
"llava_instruct_150k": "llava_instruct_150k.json",
}
# Kept for backward compatibility, `LLAVA_DATASET_FILES` is the source of truth.
LLAVA_DATASET = {
"llava_conv_58k": BASE_LLAVA_URL + "conversation_58k.json?download=true",
"llava_instruct_80k": BASE_LLAVA_URL + "llava_instruct_80k.json?download=true",
"llava_instruct_150k": BASE_LLAVA_URL + "llava_instruct_150k.json?download=true",
}
DOWNLOAD_TIMEOUT = 60
DOWNLOAD_RETRIES = 3
_COCO_DATA_URL = "http://images.cocodataset.org/train2017/"
IMAGE_TOKEN = "<image>"
MAX_SUPPORT_SEQLEN = 512
def __init__(
self,
template: Template,
model: torch.nn.Module,
tokenizer: Any,
dataset_path: str,
extra_data_dir: str | None = None,
seqlen: int = 512,
padding: bool = True,
truncation: bool = True,
nsamples: int = 512,
cache_size: int = 0,
) -> None:
super().__init__()
self.model = model
self.model_type = template.model_type
self.template = template
self.tokenizer = tokenizer
if os.path.exists(dataset_path):
logger.info(f"use dataset {dataset_path}, loading from disk...")
with open(dataset_path, "r") as f:
self.questions = json.load(f)
else:
if dataset_path == "liuhaotian/llava":
dataset_path = "llava_conv_58k"
else:
dataset_path = dataset_path.split("/")[-1]
dataset_name = dataset_path.split("/")[-1]
if dataset_name in self.LLAVA_DATASET_FILES:
logger.info(f"use dataset {dataset_name}, downloading...")
self.questions = self._download_questions(dataset_name)
else:
raise KeyError(
f"{dataset_path} is not supported; supported datasets: {', '.join(self.LLAVA_DATASET_FILES.keys())}."
)
self.seqlen = seqlen
self.questions = self.check(self.questions, self.seqlen, nsamples)
self.padding = padding
self.truncation = truncation
self.extra_data_dir = extra_data_dir
self.role_mapping = {"human": "user", "gpt": "assistant"}
self.cache_size = max(int(cache_size), 0)
self.cached_data_dict = OrderedDict() if self.cache_size > 0 else None
self.image_fold = None
if extra_data_dir is not None:
image_fold = _extract_data_dir(self.extra_data_dir)
if isinstance(image_fold, dict):
image_fold = image_fold["image"]
self.image_fold = image_fold
@classmethod
def _download_questions(cls, dataset_name: str):
"""Download a LLaVA instruction dataset and return the decoded JSON payload.
``huggingface_hub`` is preferred because it honours ``HF_TOKEN``/``HF_ENDPOINT`` mirrors,
retries transient failures and caches the file locally. A plain HTTP request is used as a
fallback. Both paths validate the payload, so a non-JSON body (an HTML error/rate-limit
page, an empty response from a proxy, ...) raises an actionable error instead of a bare
``JSONDecodeError``.
"""
filename = cls.LLAVA_DATASET_FILES[dataset_name]
errors = []
try:
from huggingface_hub import hf_hub_download
local_path = hf_hub_download(repo_id=cls.LLAVA_REPO_ID, filename=filename, repo_type="dataset")
with open(local_path, encoding="utf-8") as f:
return json.load(f)
except Exception as e:
errors.append(f"huggingface_hub: {type(e).__name__}: {e}")
logger.warning(
f"failed to fetch dataset '{dataset_name}' via huggingface_hub ({type(e).__name__}: {e}),"
" falling back to a direct http download."
)
import requests
url = cls.LLAVA_DATASET[dataset_name]
for attempt in range(1, cls.DOWNLOAD_RETRIES + 1):
try:
response = requests.get(url, timeout=cls.DOWNLOAD_TIMEOUT)
response.raise_for_status()
return json.loads(response.content.decode("utf-8"))
except Exception as e:
errors.append(f"http attempt {attempt}: {type(e).__name__}: {e}")
if attempt < cls.DOWNLOAD_RETRIES:
logger.warning(
f"failed to download dataset '{dataset_name}' from {url}"
f" ({type(e).__name__}: {e}), retrying (attempt {attempt + 1}/{cls.DOWNLOAD_RETRIES})..."
)
details = "\n ".join(errors)
raise RuntimeError(
f"could not download the calibration dataset '{dataset_name}' from"
f" '{cls.LLAVA_REPO_ID}'. Please check your network connection/proxy, or download"
f" '{filename}' manually and pass its local path via the `dataset` argument."
f"\nCauses:\n {details}"
)
def check(self, questions, word_len, nsamples):
def _check(questions, min_word_len, max_word_len, nsamples):
new_questions = []
max_len = 0
for source in questions:
str_len = 0
for text in source["conversations"]:
if self.IMAGE_TOKEN in text["value"]:
text["value"] = self.IMAGE_TOKEN + text["value"].replace(self.IMAGE_TOKEN, "")
str_len += len(text["value"].split(" "))
max_len = max(max_len, str_len)
if min_word_len <= str_len < max_word_len:
new_questions.append(source)
if len(new_questions) >= nsamples:
return new_questions
if min_word_len > max_len:
logger.debug(
f"seqlen={min_word_len} is greater than the max length of dataset {max_len},"
f" will change seqlen to {max_len - 128}"
)
new_min_word_len = max_len - 128
else:
logger.debug(
f"no enough sample for seqlen greater than {min_word_len},"
f" will decrease to {min_word_len - 128}"
)
new_min_word_len = min_word_len - 128
return new_questions + _check(questions, new_min_word_len, min_word_len, nsamples - len(new_questions))
return _check(questions, word_len, float("inf"), nsamples)
def __len__(self):
return len(self.questions)
def __getitem__(self, i) -> dict[str, torch.Tensor]:
if self.cached_data_dict is not None and i in self.cached_data_dict:
self.cached_data_dict.move_to_end(i)
return self.cached_data_dict[i]
text = self.questions[i]["conversations"]
if self.template.model_type != "llava":
text = self.covert_conversations(text)
if self.image_fold is not None:
image_path = os.path.join(self.image_fold, os.path.basename(self.questions[i]["image"]))
else:
image_path = self.questions[i]["image"]
if not os.path.exists(image_path):
image_path = self._COCO_DATA_URL + self.questions[i]["image"].split("/")[-1]
# image = self.template.processor.image_processor(image_path)
text = self.template._encode(text)
max_length = self.seqlen
truncation_strategy = "text"
ret = self.template.processor.get_input(
text=text,
images=image_path,
padding=self.padding,
truncation=self.truncation,
return_tensors="pt",
max_length=max_length,
truncation_strategy=truncation_strategy,
)
if self.cached_data_dict is not None:
self.cached_data_dict[i] = ret
self.cached_data_dict.move_to_end(i)
while len(self.cached_data_dict) > self.cache_size:
self.cached_data_dict.popitem(last=False)
return ret
def clear_runtime_cache(self):
if self.cached_data_dict is not None:
self.cached_data_dict.clear()
def covert_conversations(self, data):
new_data = []
for d in data:
content = d["value"]
if self.template.replace_tokens is not None:
for old, new in self.template.replace_tokens:
content = content.replace(old, new)
new_data.append({"role": self.role_mapping.get(d["from"], d["from"]), "content": content})
return new_data
def get_mllm_dataloader(
template,
model,
tokenizer,
processor,
image_processor=None,
dataset="liuhaotian/llava_conv_58k",
extra_data_dir=None,
seqlen=512,
bs=1,
split=None,
apply_template=None,
truncation=False,
seed=42,
nsamples=512,
quant_nontext_module=False,
):
"""Generate a DataLoader for calibration using specified parameters.
Args:
template (Template): The template to specify process for different mllms.
model (Model): The model to quantized.
tokenizer (Tokenizer): The tokenizer to use for tokenization.
Dataset_name (str): The name or path of the dataset.
extra_data_dir (str): The path for extra data such as images, audio or videos.
seqlen (int): The exact sequence length. samples < seqlen will be dropped,
samples longer than seqlen will be truncated
bs (int, optional): The batch size. Defaults to 4.
split (str, optional): The data split to use. Defaults to None.
apply_template: Whether to apply chat template in tokenization.
Returns:
DataLoader: The DataLoader for the calibrated datasets.
"""
if isinstance(template, str):
from .template import get_template
template = get_template(
template, model=model, tokenizer=tokenizer, processor=processor, image_processor=image_processor
)
if os.path.isfile(dataset) or dataset in MLLM_DATASET:
if seqlen > MLLM_DATASET[dataset].MAX_SUPPORT_SEQLEN:
logger.warning(
f"seqlen({seqlen}) is greater than the maximum length supported by the {dataset},"
f" reset to {MLLM_DATASET[dataset].MAX_SUPPORT_SEQLEN}"
)
seqlen = 512
dataset_cls = MLLM_DATASET[dataset]
dataset_kwargs = {
"seqlen": seqlen,
"truncation": truncation,
"nsamples": nsamples,
}
if "cache_size" in signature(dataset_cls.__init__).parameters:
dataset_kwargs["cache_size"] = int(os.getenv("AR_MLLM_DATASET_CACHE_SIZE", "0"))
dataset = dataset_cls(template, model, tokenizer, dataset, extra_data_dir, **dataset_kwargs)
if check_mllm_only_support_bs1(model):
bs = 1
set_seed(seed)
# Calibration should be deterministic: keep a fixed sample order.
dataloader_params = {
"batch_size": bs,
"shuffle": False,
"collate_fn": dataset.template.processor.data_collator,
}
return DataLoader(dataset, **dataloader_params), bs, seqlen
else:
# try to load text calibration dataset
from auto_round.calib_dataset import get_dataloader
dataloader = get_dataloader(tokenizer, seqlen, dataset, seed, bs, nsamples)
if quant_nontext_module:
logger.error(
"Text only dataset cannot be used for calibrating non-text modules,"
" switching to liuhaotian/llava_conv_58k"
)
sys.exit(-1)
return dataloader, bs, seqlen