├── .gitignore ├── LICENSE ├── README.md ├── lib_modelpatcher ├── __init__.py └── model_patcher.py ├── scripts └── model_patcher_hook.py └── tests ├── __init__.py ├── model_patcher_test.py └── weight_patch_test.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sd-webui-model-patcher 2 | ComfyUI style LDM patching in A1111. 3 | 4 | ## Road Map 5 | 6 | - Support all exposed APIs in ComfyUI's `ModelPatcher`. 7 | - Support patching of diffusers pipeline. 8 | - Eventually make ModelPatcher a python package that can be imported to patch any backend. 9 | 10 | ## Example 11 | 12 | Here is a code snippet from A1111's IC-Light extension that demonstrates how to use `ModelPatcher`. 13 | ```python 14 | def apply_c_concat(unet, old_forward: Callable) -> Callable: 15 | def new_forward(x, timesteps=None, context=None, **kwargs): 16 | # Expand according to batch number. 17 | c_concat = torch.cat( 18 | ([concat_conds.to(x.device)] * (x.shape[0] // concat_conds.shape[0])), 19 | dim=0, 20 | ) 21 | new_x = torch.cat([x, c_concat], dim=1) 22 | return old_forward(new_x, timesteps, context, **kwargs) 23 | 24 | return new_forward 25 | 26 | # Patch unet forward. 27 | p.model_patcher.add_module_patch( 28 | "diffusion_model", ModulePatch(create_new_forward_func=apply_c_concat) 29 | ) 30 | # Patch weights. 31 | p.model_patcher.add_patches( 32 | patches={ 33 | "diffusion_model." + key: (value.to(dtype=dtype, device=device),) 34 | for key, value in ic_model_state_dict.items() 35 | } 36 | ) 37 | ``` 38 | -------------------------------------------------------------------------------- /lib_modelpatcher/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huchenlei/sd-webui-model-patcher/307d12d970147442d3f4e9abcecfd1c4404ecf4b/lib_modelpatcher/__init__.py -------------------------------------------------------------------------------- /lib_modelpatcher/model_patcher.py: -------------------------------------------------------------------------------- 1 | # Original version from: 2 | # https://github.com/comfyanonymous/ComfyUI/blob/ffc4b7c30e35eb2773ace52a0b00e0ca5c1f4362/comfy/model_patcher.py 3 | 4 | from __future__ import annotations 5 | from collections import defaultdict 6 | from enum import Enum 7 | from typing import ( 8 | Any, 9 | Callable, 10 | Dict, 11 | Generic, 12 | List, 13 | Optional, 14 | Set, 15 | Tuple, 16 | TypeVar, 17 | ClassVar, 18 | Union, 19 | NamedTuple, 20 | ) 21 | 22 | import torch 23 | import logging 24 | from pydantic import BaseModel, Field, validator 25 | 26 | 27 | def set_attr(obj, attr, value): 28 | attrs = attr.split(".") 29 | for name in attrs[:-1]: 30 | obj = getattr(obj, name) 31 | prev = getattr(obj, attrs[-1]) 32 | setattr(obj, attrs[-1], value) 33 | return prev 34 | 35 | 36 | def get_attr(obj, attr): 37 | attrs = attr.split(".") 38 | for name in attrs: 39 | obj = getattr(obj, name) 40 | return obj 41 | 42 | 43 | def module_size(module: torch.nn.Module) -> int: 44 | """Get the memory size of a module.""" 45 | module_mem = 0 46 | sd = module.state_dict() 47 | for k in sd: 48 | t = sd[k] 49 | module_mem += t.nelement() * t.element_size() 50 | return module_mem 51 | 52 | 53 | def apply_weight_decompose(dora_scale, weight): 54 | weight_norm = ( 55 | weight.transpose(0, 1) 56 | .reshape(weight.shape[1], -1) 57 | .norm(dim=1, keepdim=True) 58 | .reshape(weight.shape[1], *[1] * (weight.dim() - 1)) 59 | .transpose(0, 1) 60 | ) 61 | 62 | return weight * (dora_scale / weight_norm).type(weight.dtype) 63 | 64 | 65 | class PatchType(Enum): 66 | DIFF = "diff" 67 | LORA = "lora" 68 | LOKR = "lokr" 69 | LOHA = "loha" 70 | GLORA = "glora" 71 | 72 | 73 | class LoRAWeight(NamedTuple): 74 | down: torch.Tensor 75 | up: torch.Tensor 76 | alpha_scale: Optional[float] = None 77 | # locon mid weights 78 | mid: Optional[torch.Tensor] = None 79 | dora_scale: Optional[torch.Tensor] = None 80 | 81 | 82 | # Represent the model to patch. 83 | ModelType = TypeVar("ModelType", bound=torch.nn.Module) 84 | # Represent the sub-module of the model to patch. 85 | ModuleType = TypeVar("ModuleType", bound=torch.nn.Module) 86 | WeightPatchWeight = Union[torch.Tensor, LoRAWeight, Tuple[torch.Tensor, ...]] 87 | CastToDeviceFunc = Callable[[torch.Tensor, torch.device, torch.dtype], torch.Tensor] 88 | 89 | 90 | class WeightPatch(BaseModel): 91 | """Patch to apply on model weight.""" 92 | 93 | class Config: 94 | arbitrary_types_allowed = True 95 | extra = "ignore" 96 | 97 | cls_logger: ClassVar[logging.Logger] = logging.Logger("WeightPatch") 98 | cls_cast_to_device: ClassVar[CastToDeviceFunc] = lambda t, device, dtype: t.to( 99 | device, dtype 100 | ) 101 | 102 | weight: WeightPatchWeight 103 | patch_type: PatchType = PatchType.DIFF 104 | # The scale applied on patch weight value. 105 | alpha: float = 1.0 106 | # The scale applied on the model weight value. 107 | strength_model: float = 1.0 108 | 109 | def apply( 110 | self, model_weight: torch.Tensor, key: Optional[str] = None 111 | ) -> torch.Tensor: 112 | """Apply the patch to model weight.""" 113 | if self.strength_model != 1.0: 114 | model_weight *= self.strength_model 115 | 116 | try: 117 | if self.patch_type == PatchType.DIFF: 118 | assert isinstance(self.weight, torch.Tensor) 119 | return self._patch_diff(model_weight, key) 120 | elif self.patch_type == PatchType.LORA: 121 | assert isinstance(self.weight, LoRAWeight) 122 | return self._patch_lora(model_weight) 123 | else: 124 | raise NotImplementedError( 125 | f"Patch type {self.patch_type} is not implemented." 126 | ) 127 | except ValueError as e: 128 | logging.error("ERROR {} {} {}".format(self.patch_type, key, e)) 129 | return model_weight 130 | 131 | def _patch_diff_expand(self, model_weight: torch.Tensor, key: str) -> torch.Tensor: 132 | """Unet input only. Used for the model to accept more input concats.""" 133 | new_shape = [max(n, m) for n, m in zip(self.weight.shape, model_weight.shape)] 134 | WeightPatch.cls_logger.info( 135 | f"Merged with {key} channel changed from {model_weight.shape} to {new_shape}" 136 | ) 137 | new_diff = self.alpha * WeightPatch.cls_cast_to_device( 138 | self.weight, model_weight.device, model_weight.dtype 139 | ) 140 | new_weight = torch.zeros(size=new_shape).to(model_weight) 141 | new_weight[ 142 | : model_weight.shape[0], 143 | : model_weight.shape[1], 144 | : model_weight.shape[2], 145 | : model_weight.shape[3], 146 | ] = model_weight 147 | new_weight[ 148 | : new_diff.shape[0], 149 | : new_diff.shape[1], 150 | : new_diff.shape[2], 151 | : new_diff.shape[3], 152 | ] += new_diff 153 | return new_weight.contiguous().clone() 154 | 155 | def _patch_diff(self, model_weight: torch.Tensor, key: str) -> torch.Tensor: 156 | """Apply the diff patch to model weight.""" 157 | if self.alpha != 0.0: 158 | if self.weight.shape != model_weight.shape: 159 | if model_weight.ndim == self.weight.ndim == 4: 160 | return self._patch_diff_expand(model_weight, key) 161 | 162 | raise ValueError( 163 | "WARNING SHAPE MISMATCH WEIGHT NOT MERGED {} != {}".format( 164 | self.weight.shape, model_weight.shape 165 | ) 166 | ) 167 | else: 168 | return model_weight + self.alpha * self.weight.to(model_weight.device) 169 | return model_weight 170 | 171 | def _patch_lora(self, model_weight: torch.Tensor) -> torch.Tensor: 172 | """Apply the lora/locon patch to model weight.""" 173 | v: LoRAWeight = self.weight 174 | alpha = self.alpha 175 | weight = model_weight 176 | 177 | mat1 = WeightPatch.cls_cast_to_device(v.down, weight.device, torch.float32) 178 | mat2 = WeightPatch.cls_cast_to_device(v.up, weight.device, torch.float32) 179 | dora_scale = v.dora_scale 180 | 181 | if v.alpha_scale is not None: 182 | alpha *= v.alpha_scale / mat2.shape[0] 183 | if v.mid is not None: 184 | # locon mid weights, hopefully the math is fine because I didn't properly test it 185 | mat3 = WeightPatch.cls_cast_to_device(v.mid, weight.device, torch.float32) 186 | final_shape = [mat2.shape[1], mat2.shape[0], mat3.shape[2], mat3.shape[3]] 187 | mat2 = ( 188 | torch.mm( 189 | mat2.transpose(0, 1).flatten(start_dim=1), 190 | mat3.transpose(0, 1).flatten(start_dim=1), 191 | ) 192 | .reshape(final_shape) 193 | .transpose(0, 1) 194 | ) 195 | weight += ( 196 | (alpha * torch.mm(mat1.flatten(start_dim=1), mat2.flatten(start_dim=1))) 197 | .reshape(weight.shape) 198 | .type(weight.dtype) 199 | ) 200 | if dora_scale is not None: 201 | weight = apply_weight_decompose( 202 | WeightPatch.cls_cast_to_device( 203 | dora_scale, weight.device, torch.float32 204 | ), 205 | weight, 206 | ) 207 | return weight 208 | 209 | 210 | class ModulePatch(BaseModel, Generic[ModuleType]): 211 | """Patch to replace a module in the model.""" 212 | 213 | create_new_forward_func: Callable[[ModuleType, Callable], Callable] 214 | 215 | 216 | class ModelPatcher(BaseModel, Generic[ModelType]): 217 | class Config: 218 | arbitrary_types_allowed = True 219 | extra = "ignore" 220 | 221 | cls_logger: ClassVar[logging.Logger] = logging.Logger( 222 | "ModelPatcher", level=logging.INFO 223 | ) 224 | cls_strict: ClassVar[bool] = False 225 | 226 | # The managed model of the model patcher. 227 | model: ModelType = Field(immutable=True) 228 | # The device to run inference on. 229 | load_device: torch.device = Field(immutable=True) 230 | # The device to offload the model to. 231 | offload_device: torch.device = Field(immutable=True) 232 | # Whether to update weight in place. 233 | weight_inplace_update: bool = Field(immutable=True, default=False) 234 | 235 | # The current device the model is stored on. 236 | current_device: torch.device = None 237 | 238 | @validator("current_device", pre=True, always=True) 239 | def set_current_device(cls, v, values): 240 | return values.get("offload_device") if v is None else v 241 | 242 | # The size of the model in number of bytes. 243 | model_size: int = None 244 | 245 | @validator("model_size", pre=True, always=True) 246 | def set_model_size(cls, v, values): 247 | model: ModelType = values.get("model") 248 | return module_size(model) if v is None else v 249 | 250 | model_keys: Set[str] = None 251 | 252 | @validator("model_keys", pre=True, always=True) 253 | def set_model_keys(cls, v, values): 254 | model: ModelType = values.get("model") 255 | return set(model.state_dict().keys()) if v is None else v 256 | 257 | # The optional name of the ModelPatcher for debug purpose. 258 | name: str = Field(immutable=True, default="ModelPatcher") 259 | 260 | # Patches applied to module weights. 261 | weight_patches: Dict[str, List[WeightPatch]] = Field( 262 | default_factory=lambda: defaultdict(list) 263 | ) 264 | # Store weights before patching. 265 | weight_backup: Dict[str, torch.Tensor] = Field(default_factory=dict) 266 | 267 | # Patches applied to model's torch modules. 268 | module_patches: Dict[str, List[ModulePatch]] = Field( 269 | default_factory=lambda: defaultdict(list) 270 | ) 271 | # Store modules before patching. 272 | module_backup: Dict[str, Callable] = Field(default_factory=dict) 273 | # Whether the model is patched. 274 | is_patched: bool = False 275 | 276 | def add_weight_patch(self, key: str, weight_patch: WeightPatch) -> bool: 277 | if key not in self.model_keys: 278 | if self.cls_strict: 279 | raise ValueError(f"Key {key} not found in model.") 280 | else: 281 | return False 282 | self.weight_patches[key].append(weight_patch) 283 | 284 | def add_weight_patches(self, weight_patches: Dict[str, WeightPatch]) -> List[str]: 285 | return [ 286 | key 287 | for key, weight_patch in weight_patches.items() 288 | if self.add_weight_patch(key, weight_patch) 289 | ] 290 | 291 | def add_patches( 292 | self, 293 | patches: Dict[str, Union[Tuple[torch.Tensor], Tuple[str, torch.Tensor]]], 294 | strength_patch: float = 1.0, 295 | strength_model: float = 1.0, 296 | ): 297 | """ComfyUI-compatible interface to add weight patches.""" 298 | 299 | def parse_value( 300 | v: Union[Tuple[torch.Tensor], Tuple[str, torch.Tensor]] 301 | ) -> Tuple[torch.Tensor, PatchType]: 302 | if len(v) == 1: 303 | return dict(weight=v[0], patch_type=PatchType.DIFF) 304 | else: 305 | assert len(v) == 2, f"Invalid patch value {v}." 306 | return dict(weight=v[1], patch_type=PatchType(v[0])) 307 | 308 | return self.add_weight_patches( 309 | { 310 | key: WeightPatch( 311 | **parse_value(value), 312 | alpha=strength_patch, 313 | strength_model=strength_model, 314 | ) 315 | for key, value in patches.items() 316 | } 317 | ) 318 | 319 | def clone(self): 320 | """ComfyUI-compatible interface to clone the model patcher.""" 321 | # TODO: Check everything works as expected. 322 | # Some fields might needs explicit copy. 323 | return self.copy() 324 | 325 | def __repr__(self): 326 | return f"ModelPatcher(model={self.model.__class__}, model_size={self.model_size}, is_patched={self.is_patched})" 327 | 328 | def to( 329 | self, 330 | device: Optional[torch.device] = None, 331 | dtype: Optional[torch.dtype] = None, 332 | ): 333 | self.model.to(device=device, dtype=dtype) 334 | if device is not None: 335 | self.current_device = device 336 | return self 337 | 338 | def get_attr(self, key: str) -> Optional[Any]: 339 | if key == ".": 340 | return self.model 341 | return get_attr(self.model, key) 342 | 343 | def set_attr(self, key: str, value: Any) -> Any: 344 | if key == ".": 345 | value = getattr(self.model, key) 346 | setattr(self.model, key, value) 347 | return value 348 | 349 | return set_attr(self.model, key, value) 350 | 351 | def set_attr_param(self, attr, value): 352 | return self.set_attr(attr, torch.nn.Parameter(value, requires_grad=False)) 353 | 354 | def copy_to_param(self, attr, value): 355 | """inplace update tensor instead of replacing it""" 356 | attrs = attr.split(".") 357 | obj = self.model 358 | for name in attrs[:-1]: 359 | obj = getattr(obj, name) 360 | prev = getattr(obj, attrs[-1]) 361 | prev.data.copy_(value) 362 | 363 | def add_module_patch(self, key: str, module_patch: ModulePatch) -> bool: 364 | target_module = self.get_attr(key) 365 | if target_module is None: 366 | if self.cls_strict: 367 | raise ValueError(f"Key {key} not found in model.") 368 | return False 369 | 370 | self.module_patches[key].append(module_patch) 371 | return True 372 | 373 | def _patch_modules(self): 374 | for key, module_patches in self.module_patches.items(): 375 | module = self.get_attr(key) 376 | old_forward = module.forward 377 | self.module_backup[key] = old_forward 378 | for module_patch in module_patches: 379 | module.forward = module_patch.create_new_forward_func( 380 | module, module.forward 381 | ) 382 | 383 | def _patch_weights(self): 384 | for key, weight_patches in self.weight_patches.items(): 385 | assert key in self.model_keys, f"Key {key} not found in model." 386 | old_weight = self.get_attr(key) 387 | self.weight_backup[key] = old_weight 388 | 389 | new_weight = old_weight 390 | for weight_patch in weight_patches: 391 | new_weight = weight_patch.apply(new_weight, key) 392 | 393 | if self.weight_inplace_update: 394 | self.copy_to_param(key, new_weight) 395 | else: 396 | self.set_attr_param(key, new_weight) 397 | 398 | def patch_model(self, patch_weights: bool = True): 399 | assert not self.is_patched, "Model is already patched." 400 | self._patch_modules() 401 | if patch_weights: 402 | self._patch_weights() 403 | self.is_patched = True 404 | return self.model 405 | 406 | def _unpatch_weights(self): 407 | for k, v in self.weight_backup.items(): 408 | if self.weight_inplace_update: 409 | self.copy_to_param(k, v) 410 | else: 411 | self.set_attr_param(k, v) 412 | self.weight_backup.clear() 413 | 414 | def _unpatch_modules(self): 415 | for k, v in self.module_backup.items(): 416 | module = self.get_attr(k) 417 | module.forward = v 418 | self.module_backup.clear() 419 | 420 | def unpatch_model(self, unpatch_weights=True): 421 | assert self.is_patched, "Model is not patched." 422 | if unpatch_weights: 423 | self._unpatch_weights() 424 | self.is_patched = False 425 | self._unpatch_modules() 426 | 427 | def close(self): 428 | """Properly free VRAM by clearing reference to tensors and modules.""" 429 | assert not self.is_patched 430 | assert len(self.weight_backup) == 0 431 | assert len(self.module_backup) == 0 432 | self.module_patches.clear() 433 | self.weight_patches.clear() 434 | -------------------------------------------------------------------------------- /scripts/model_patcher_hook.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import logging 3 | import functools 4 | from typing import Callable 5 | 6 | from modules.processing import ( 7 | StableDiffusionProcessing, 8 | StableDiffusionProcessingTxt2Img, 9 | StableDiffusionProcessingImg2Img, 10 | ) 11 | from modules.sd_samplers_common import Sampler 12 | from modules import devices 13 | 14 | from lib_modelpatcher.model_patcher import ModelPatcher 15 | 16 | 17 | def model_patcher_hook(logger: logging.Logger): 18 | """Patches StableDiffusionProcessing to add 19 | - model_patcher 20 | - hr_model_patcher 21 | - get_model_patcher 22 | fields to StableDiffusionProcessing classes, and apply patches before 23 | calling sample methods 24 | """ 25 | 26 | def hook_init(patcher_field_name: str): 27 | def decorator(func: Callable) -> Callable: 28 | @functools.wraps(func) 29 | def wrapped_init_func(self: StableDiffusionProcessing, *args, **kwargs): 30 | result = func(self, *args, **kwargs) 31 | 32 | sd_ldm = self.sd_model 33 | assert sd_ldm is not None 34 | load_device = devices.get_optimal_device() 35 | offload_device = devices.cpu 36 | 37 | setattr( 38 | self, 39 | patcher_field_name, 40 | ModelPatcher( 41 | model=sd_ldm.model, 42 | load_device=load_device, 43 | offload_device=offload_device, 44 | name=f"{patcher_field_name} of {self.__class__.__name__}", 45 | ), 46 | ) 47 | logger.info(f"Init p.{patcher_field_name}.") 48 | return result 49 | 50 | return wrapped_init_func 51 | 52 | return decorator 53 | 54 | StableDiffusionProcessingTxt2Img.__init__ = hook_init("model_patcher")( 55 | StableDiffusionProcessingTxt2Img.__init__ 56 | ) 57 | StableDiffusionProcessingTxt2Img.__init__ = hook_init("hr_model_patcher")( 58 | StableDiffusionProcessingTxt2Img.__init__ 59 | ) 60 | StableDiffusionProcessingImg2Img.__init__ = hook_init("model_patcher")( 61 | StableDiffusionProcessingImg2Img.__init__ 62 | ) 63 | logger.info("__init__ hooks applied") 64 | 65 | def hook_close(patcher_field_name: str): 66 | def decorator(func: Callable) -> Callable: 67 | @functools.wraps(func) 68 | def wrapped_close_func(self: StableDiffusionProcessing, *args, **kwargs): 69 | patcher: ModelPatcher = getattr(self, patcher_field_name) 70 | assert isinstance(patcher, ModelPatcher) 71 | patcher.close() 72 | logger.info(f"Close p.{patcher_field_name}.") 73 | return func(self, *args, **kwargs) 74 | 75 | return wrapped_close_func 76 | 77 | return decorator 78 | 79 | StableDiffusionProcessingTxt2Img.close = hook_close("model_patcher")( 80 | StableDiffusionProcessingTxt2Img.close 81 | ) 82 | StableDiffusionProcessingTxt2Img.close = hook_close("hr_model_patcher")( 83 | StableDiffusionProcessingTxt2Img.close 84 | ) 85 | StableDiffusionProcessingImg2Img.close = hook_close("model_patcher")( 86 | StableDiffusionProcessingImg2Img.close 87 | ) 88 | logger.info("close hooks applied") 89 | 90 | def hook_sample(): 91 | def decorator(func: Callable) -> Callable: 92 | @functools.wraps(func) 93 | def wrapped_sample_func(self: Sampler, *args, **kwargs): 94 | patcher: ModelPatcher = self.p.get_model_patcher() 95 | assert isinstance(patcher, ModelPatcher) 96 | patcher.patch_model() 97 | logger.info(f"Patch {patcher.name}.") 98 | 99 | try: 100 | return func(self, *args, **kwargs) 101 | finally: 102 | patcher.unpatch_model() 103 | logger.info(f"Unpatch {patcher.name}.") 104 | 105 | return wrapped_sample_func 106 | 107 | return decorator 108 | 109 | Sampler.launch_sampling = hook_sample()(Sampler.launch_sampling) 110 | logger.info("sample hooks applied") 111 | 112 | def get_model_patcher(self: StableDiffusionProcessing) -> ModelPatcher: 113 | if isinstance(self, StableDiffusionProcessingTxt2Img) and self.is_hr_pass: 114 | return self.hr_model_patcher 115 | return self.model_patcher 116 | 117 | StableDiffusionProcessing.get_model_patcher = get_model_patcher 118 | 119 | 120 | def create_logger(): 121 | logger = logging.getLogger(__name__) 122 | logger.setLevel(logging.INFO) 123 | if not logger.handlers: 124 | handler = logging.StreamHandler(sys.stdout) 125 | handler.setFormatter( 126 | logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") 127 | ) 128 | logger.addHandler(handler) 129 | return logger 130 | 131 | 132 | model_patcher_hook(create_logger()) 133 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huchenlei/sd-webui-model-patcher/307d12d970147442d3f4e9abcecfd1c4404ecf4b/tests/__init__.py -------------------------------------------------------------------------------- /tests/model_patcher_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import torch 3 | 4 | from lib_modelpatcher.model_patcher import ModelPatcher, ModulePatch, WeightPatch 5 | 6 | 7 | def test_model_patcher_creation(): 8 | model = torch.nn.Linear(10, 10) 9 | load_device = torch.device("cuda:0") 10 | offload_device = torch.device("cpu") 11 | 12 | model_patcher = ModelPatcher( 13 | model=model, 14 | load_device=load_device, 15 | offload_device=offload_device, 16 | ) 17 | 18 | assert model_patcher.model == model 19 | assert model_patcher.load_device == load_device 20 | assert model_patcher.offload_device == offload_device 21 | assert model_patcher.is_patched is False 22 | 23 | 24 | class SampleModel(torch.nn.Module): 25 | def __init__(self): 26 | super(SampleModel, self).__init__() 27 | self.fc1 = torch.nn.Linear(10, 10) 28 | self.fc2 = torch.nn.Linear(10, 10) 29 | 30 | def init_identity_linear(self): 31 | with torch.no_grad(): 32 | self.fc1.weight.copy_(torch.eye(10)) 33 | self.fc1.bias.copy_(torch.zeros(10)) 34 | self.fc2.weight.copy_(torch.eye(10)) 35 | self.fc2.bias.copy_(torch.zeros(10)) 36 | 37 | def forward(self, x): 38 | x = self.fc1(x) 39 | x = self.fc2(x) 40 | return x 41 | 42 | 43 | @pytest.mark.parametrize("module_key", ["fc1", "fc2", "."]) 44 | def test_model_patcher_module_patch(module_key: str): 45 | load_device = torch.device("cpu") # TODO: Change to cuda:0 when running locally 46 | offload_device = torch.device("cpu") 47 | 48 | model = SampleModel() 49 | model.init_identity_linear() 50 | 51 | model = model.to(load_device) 52 | input_tensor = torch.randn(10, 10).to(load_device) 53 | assert torch.allclose( 54 | model(input_tensor), input_tensor 55 | ), "Model is identity transformation before patching" 56 | 57 | model_patcher = ModelPatcher( 58 | model=model, 59 | load_device=load_device, 60 | offload_device=offload_device, 61 | ).to(load_device) 62 | 63 | def create_new_forward(module, old_forward): 64 | def new_forward(x): 65 | return old_forward(x) + 1.0 66 | 67 | return new_forward 68 | 69 | model_patcher.add_module_patch( 70 | key=module_key, module_patch=ModulePatch(create_new_forward_func=create_new_forward) 71 | ) 72 | assert model_patcher.is_patched is False 73 | model_patcher.patch_model() 74 | assert model_patcher.is_patched is True 75 | assert torch.allclose( 76 | model(input_tensor), input_tensor + 1.0 77 | ), "Model is not identity transformation after patching" 78 | 79 | model_patcher.unpatch_model() 80 | assert model_patcher.is_patched is False 81 | assert torch.allclose( 82 | model(input_tensor), input_tensor 83 | ), "Model is identity transformation after unpatching" 84 | 85 | 86 | def test_model_patcher_weight_patch(): 87 | load_device = torch.device("cpu") # TODO: Change to cuda:0 when running locally 88 | offload_device = torch.device("cpu") 89 | 90 | model = SampleModel() 91 | model.init_identity_linear() 92 | 93 | model = model.to(load_device) 94 | input_tensor = torch.randn(10, 10).to(load_device) 95 | assert torch.allclose( 96 | model(input_tensor), input_tensor 97 | ), "Model is identity transformation before patching" 98 | 99 | model_patcher = ModelPatcher( 100 | model=model, 101 | load_device=load_device, 102 | offload_device=offload_device, 103 | ).to(load_device) 104 | 105 | model_patcher.add_weight_patch( 106 | key="fc1.bias", weight_patch=WeightPatch(weight=2.0 * torch.ones_like(model.fc1.bias)) 107 | ) 108 | assert model_patcher.is_patched is False 109 | model_patcher.patch_model() 110 | assert model_patcher.is_patched is True 111 | assert torch.allclose( 112 | model(input_tensor), input_tensor + 2.0 113 | ), "Model is not identity transformation after patching" 114 | 115 | model_patcher.unpatch_model() 116 | assert model_patcher.is_patched is False 117 | assert torch.allclose( 118 | model(input_tensor), input_tensor 119 | ), "Model is identity transformation after unpatching" 120 | -------------------------------------------------------------------------------- /tests/weight_patch_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import torch 3 | 4 | from lib_modelpatcher.model_patcher import ( 5 | LoRAWeight, 6 | WeightPatch, 7 | PatchType, 8 | ) 9 | 10 | 11 | def test_patch_diff(): 12 | weight = torch.tensor([1, 2, 3, 4]) 13 | patch = WeightPatch( 14 | weight=torch.tensor([0.5, 0.5, 0.5, -0.5]), patch_type=PatchType.DIFF, alpha=0.5 15 | ) 16 | patched_weight = patch.apply(weight) 17 | expected_weight = torch.tensor([1.25, 2.25, 3.25, 3.75]) 18 | assert torch.all(torch.eq(patched_weight, expected_weight)) 19 | 20 | 21 | target_weight = weight = torch.tensor( 22 | [ 23 | [1, 1], 24 | [1, 1], 25 | ] 26 | ) 27 | down_mat = torch.tensor( 28 | [ 29 | [2, 2], 30 | [2, 2], 31 | ] 32 | ) 33 | 34 | up_mat = torch.tensor( 35 | [ 36 | [4, 4], 37 | [4, 4], 38 | ] 39 | ) 40 | 41 | 42 | @pytest.mark.parametrize( 43 | "test_case", 44 | [ 45 | ( 46 | LoRAWeight( 47 | down=down_mat, 48 | up=up_mat, 49 | ), 50 | target_weight + (down_mat @ up_mat), 51 | ), 52 | ], 53 | ) 54 | def test_patch_lora(test_case): 55 | lora_weight, expected_weight = test_case 56 | patch = WeightPatch( 57 | weight=lora_weight, 58 | patch_type=PatchType.LORA, 59 | alpha=1.0, 60 | ) 61 | patched_weight = patch.apply(weight) 62 | assert torch.all( 63 | torch.eq(patched_weight, expected_weight) 64 | ), f"{patched_weight} != {expected_weight}" 65 | 66 | 67 | --------------------------------------------------------------------------------