|
| 1 | +import os |
| 2 | +import shutil |
| 3 | +from concurrent.futures import ThreadPoolExecutor, as_completed |
| 4 | +from pathlib import Path |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +import torch |
| 8 | +import tqdm |
| 9 | +from compressed_tensors.quantization import QuantizationScheme |
| 10 | +from compressed_tensors.utils.match import _match_name |
| 11 | +from loguru import logger |
| 12 | +from safetensors.torch import load_file, save_file |
| 13 | + |
| 14 | +from llmcompressor.entrypoints.model_free.helpers import ( |
| 15 | + gpu_if_available, |
| 16 | + validate_scheme, |
| 17 | +) |
| 18 | +from llmcompressor.entrypoints.model_free.lifecycle import ( |
| 19 | + calibrate_weights, |
| 20 | + compress_module, |
| 21 | + initialize_quantized_linear, |
| 22 | +) |
| 23 | +from llmcompressor.entrypoints.model_free.model_utils import ( |
| 24 | + get_checkpoint_files, |
| 25 | + is_weights_file, |
| 26 | +) |
| 27 | +from llmcompressor.entrypoints.model_free.save_utils import ( |
| 28 | + update_config, |
| 29 | + update_safetensors_index, |
| 30 | +) |
| 31 | + |
| 32 | +__all__ = ["model_free_ptq"] |
| 33 | + |
| 34 | + |
| 35 | +def model_free_ptq( |
| 36 | + model_stub: str | os.PathLike, |
| 37 | + save_directory: str | os.PathLike, |
| 38 | + scheme: QuantizationScheme | str, |
| 39 | + ignore: Optional[list[str]] = None, |
| 40 | + max_workers: int = 1, |
| 41 | + device: Optional[torch.device | str] = None, |
| 42 | +): |
| 43 | + """ |
| 44 | + Quantize a model without the need for a model definition. This function operates on |
| 45 | + a model stub or folder containing weights saved in safetensors files |
| 46 | +
|
| 47 | + :param model_stub: huggingface model hub or path to local weights files |
| 48 | + :param scheme: weight quantization scheme or preset scheme name |
| 49 | + :param ignore: modules to ignore. Modules ending with "norm" are automatically |
| 50 | + ignored |
| 51 | + :param max_workers: number of worker threads to process files with |
| 52 | + :param device: gpu device to accelerate quantization with |
| 53 | + """ |
| 54 | + # validate arguments |
| 55 | + model_files = get_checkpoint_files(model_stub) |
| 56 | + scheme_name, scheme = validate_scheme(scheme) |
| 57 | + device = gpu_if_available(device) |
| 58 | + |
| 59 | + # 0. collect safetensors files, copy files |
| 60 | + jobs = [] |
| 61 | + for file_path, resolved_path in model_files: |
| 62 | + save_path = Path(save_directory) / file_path |
| 63 | + |
| 64 | + if file_path.endswith("safetensors"): |
| 65 | + jobs.append( |
| 66 | + (_process_file, resolved_path, save_path, scheme, ignore, device) |
| 67 | + ) |
| 68 | + |
| 69 | + else: |
| 70 | + if is_weights_file(file_path): |
| 71 | + logger.warning(f"Skipping weights file {file_path}") |
| 72 | + save_path.parent.mkdir(parents=True, exist_ok=True) |
| 73 | + logger.info(f"Copying {file_path} {save_path}") |
| 74 | + shutil.copyfile(resolved_path, save_path) |
| 75 | + |
| 76 | + # 1-4. quantize and compress weights |
| 77 | + with ThreadPoolExecutor(max_workers) as executor: |
| 78 | + futures = [executor.submit(*job) for job in jobs] |
| 79 | + |
| 80 | + total_size = 0 |
| 81 | + weight_map = dict() |
| 82 | + for future in tqdm.tqdm( |
| 83 | + as_completed(futures), total=len(futures), desc="Quantizing" |
| 84 | + ): |
| 85 | + _total_size, _weight_map = future.result() |
| 86 | + total_size += _total_size |
| 87 | + weight_map.update(_weight_map) |
| 88 | + |
| 89 | + # 5. update config and safetensors index |
| 90 | + update_config(save_directory, scheme_name, scheme, ignore) |
| 91 | + update_safetensors_index(save_directory, total_size, weight_map) |
| 92 | + |
| 93 | + |
| 94 | +def _process_file( |
| 95 | + file_path: str | os.PathLike, |
| 96 | + save_path: str | os.PathLike, |
| 97 | + scheme: QuantizationScheme, |
| 98 | + ignore: str | list[str], |
| 99 | + device: str | torch.device, |
| 100 | +) -> tuple[int, dict[str, str]]: |
| 101 | + """ |
| 102 | + Quantize and compress tensors in a given safetensors file |
| 103 | +
|
| 104 | + :param file_path: safetensors file to process |
| 105 | + :param save_path: save path of file with quantized weights |
| 106 | + :param scheme: quantization scheme to apply to tensors |
| 107 | + :param ignore: modules to ignore. Modules ending with "norm" are automatically |
| 108 | + ignored |
| 109 | + :param device: device used to quantize and compress weights |
| 110 | + """ |
| 111 | + tensors = load_file(file_path) |
| 112 | + |
| 113 | + for name in list(tensors.keys()): |
| 114 | + module_name, param_name = name.rsplit(".", 1) |
| 115 | + is_linear_weight = param_name == "weight" and not module_name.endswith("norm") |
| 116 | + is_ignored = any(_match_name(module_name, ign) for ign in ignore) |
| 117 | + if not is_linear_weight or is_ignored: |
| 118 | + continue |
| 119 | + |
| 120 | + # 1. initialize module with qparams (on device) |
| 121 | + module = initialize_quantized_linear(tensors[name], scheme, device) |
| 122 | + |
| 123 | + # 2. calibrate weight qparams |
| 124 | + calibrate_weights(module) |
| 125 | + |
| 126 | + # 3. compress module using qparams |
| 127 | + compress_module(module) |
| 128 | + |
| 129 | + # 4. save compressed data (on cpu) |
| 130 | + del tensors[name] |
| 131 | + prefix = module_name + "." |
| 132 | + for key, value in module.state_dict(prefix=prefix).items(): |
| 133 | + tensors[key] = value.to("cpu") |
| 134 | + |
| 135 | + save_file(tensors, save_path) |
| 136 | + total_size = sum(tensor.nbytes for tensor in tensors.values()) |
| 137 | + weight_map = {key: os.path.basename(save_path) for key in tensors.keys()} |
| 138 | + return total_size, weight_map |
0 commit comments