|
| 1 | +import json |
| 2 | +import os |
| 3 | +from typing import Union |
| 4 | + |
| 5 | +from diffusers.models.model_loading_utils import load_state_dict |
| 6 | +from diffusers.utils import ( |
| 7 | + CONFIG_NAME, |
| 8 | + SAFE_WEIGHTS_INDEX_NAME, |
| 9 | + SAFETENSORS_WEIGHTS_NAME, |
| 10 | + _get_checkpoint_shard_files, |
| 11 | + is_accelerate_available, |
| 12 | +) |
| 13 | +from optimum.quanto.models import QuantizedDiffusersModel |
| 14 | +from optimum.quanto.models.shared_dict import ShardedStateDict |
| 15 | + |
| 16 | +from invokeai.backend.requantize import requantize |
| 17 | + |
| 18 | + |
| 19 | +class FastQuantizedDiffusersModel(QuantizedDiffusersModel): |
| 20 | + @classmethod |
| 21 | + def from_pretrained(cls, model_name_or_path: Union[str, os.PathLike]): |
| 22 | + """We override the `from_pretrained()` method in order to use our custom `requantize()` implementation.""" |
| 23 | + if cls.base_class is None: |
| 24 | + raise ValueError("The `base_class` attribute needs to be configured.") |
| 25 | + |
| 26 | + if not is_accelerate_available(): |
| 27 | + raise ValueError("Reloading a quantized diffusers model requires the accelerate library.") |
| 28 | + from accelerate import init_empty_weights |
| 29 | + |
| 30 | + if os.path.isdir(model_name_or_path): |
| 31 | + # Look for a quantization map |
| 32 | + qmap_path = os.path.join(model_name_or_path, cls._qmap_name()) |
| 33 | + if not os.path.exists(qmap_path): |
| 34 | + raise ValueError(f"No quantization map found in {model_name_or_path}: is this a quantized model ?") |
| 35 | + |
| 36 | + # Look for original model config file. |
| 37 | + model_config_path = os.path.join(model_name_or_path, CONFIG_NAME) |
| 38 | + if not os.path.exists(model_config_path): |
| 39 | + raise ValueError(f"{CONFIG_NAME} not found in {model_name_or_path}.") |
| 40 | + |
| 41 | + with open(qmap_path, "r", encoding="utf-8") as f: |
| 42 | + qmap = json.load(f) |
| 43 | + |
| 44 | + with open(model_config_path, "r", encoding="utf-8") as f: |
| 45 | + original_model_cls_name = json.load(f)["_class_name"] |
| 46 | + configured_cls_name = cls.base_class.__name__ |
| 47 | + if configured_cls_name != original_model_cls_name: |
| 48 | + raise ValueError( |
| 49 | + f"Configured base class ({configured_cls_name}) differs from what was derived from the provided configuration ({original_model_cls_name})." |
| 50 | + ) |
| 51 | + |
| 52 | + # Create an empty model |
| 53 | + config = cls.base_class.load_config(model_name_or_path) |
| 54 | + with init_empty_weights(): |
| 55 | + model = cls.base_class.from_config(config) |
| 56 | + |
| 57 | + # Look for the index of a sharded checkpoint |
| 58 | + checkpoint_file = os.path.join(model_name_or_path, SAFE_WEIGHTS_INDEX_NAME) |
| 59 | + if os.path.exists(checkpoint_file): |
| 60 | + # Convert the checkpoint path to a list of shards |
| 61 | + _, sharded_metadata = _get_checkpoint_shard_files(model_name_or_path, checkpoint_file) |
| 62 | + # Create a mapping for the sharded safetensor files |
| 63 | + state_dict = ShardedStateDict(model_name_or_path, sharded_metadata["weight_map"]) |
| 64 | + else: |
| 65 | + # Look for a single checkpoint file |
| 66 | + checkpoint_file = os.path.join(model_name_or_path, SAFETENSORS_WEIGHTS_NAME) |
| 67 | + if not os.path.exists(checkpoint_file): |
| 68 | + raise ValueError(f"No safetensor weights found in {model_name_or_path}.") |
| 69 | + # Get state_dict from model checkpoint |
| 70 | + state_dict = load_state_dict(checkpoint_file) |
| 71 | + |
| 72 | + # Requantize and load quantized weights from state_dict |
| 73 | + requantize(model, state_dict=state_dict, quantization_map=qmap) |
| 74 | + model.eval() |
| 75 | + return cls(model) |
| 76 | + else: |
| 77 | + raise NotImplementedError("Reloading quantized models directly from the hub is not supported yet.") |
0 commit comments