text
stringlengths
1
1.02k
class_index
int64
0
1.38k
source
stringclasses
431 values
Whether to disable mmap when loading a Safetensors model. This option can perform better when the model is on a network mount or hard drive, which may not handle the seeky-ness of mmap very well. kwargs (remaining dictionary of keyword arguments, *optional*): Can be used to o...
1,259
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_model.py
```py >>> from diffusers import StableCascadeUNet >>> ckpt_path = "https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_b_lite.safetensors" >>> model = StableCascadeUNet.from_single_file(ckpt_path) ``` """ mapping_class_name = _get_single_file_loadable_mapp...
1,259
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_model.py
pretrained_model_link_or_path = kwargs.get("pretrained_model_link_or_path", None) if pretrained_model_link_or_path is not None: deprecation_message = ( "Please use `pretrained_model_link_or_path_or_dict` argument instead for model classes" ) deprecate("pretrai...
1,259
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_model.py
force_download = kwargs.pop("force_download", False) proxies = kwargs.pop("proxies", None) token = kwargs.pop("token", None) cache_dir = kwargs.pop("cache_dir", None) local_files_only = kwargs.pop("local_files_only", None) subfolder = kwargs.pop("subfolder", None) revisio...
1,259
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_model.py
if isinstance(pretrained_model_link_or_path_or_dict, dict): checkpoint = pretrained_model_link_or_path_or_dict else: checkpoint = load_single_file_checkpoint( pretrained_model_link_or_path_or_dict, force_download=force_download, proxies=pro...
1,259
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_model.py
checkpoint_mapping_fn = mapping_functions["checkpoint_mapping_fn"] if original_config is not None: if "config_mapping_fn" in mapping_functions: config_mapping_fn = mapping_functions["config_mapping_fn"] else: config_mapping_fn = None if config...
1,259
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_model.py
config_mapping_kwargs = _get_mapping_function_kwargs(config_mapping_fn, **kwargs) diffusers_model_config = config_mapping_fn( original_config=original_config, checkpoint=checkpoint, **config_mapping_kwargs ) else: if config is not None: if isin...
1,259
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_model.py
if "default_subfolder" in mapping_functions: subfolder = mapping_functions["default_subfolder"] subfolder = subfolder or config.pop( "subfolder", None ) # some configs contain a subfolder key, e.g. StableCascadeUNet diffusers_model_c...
1,259
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_model.py
# Map legacy kwargs to new kwargs if "legacy_kwargs" in mapping_functions: legacy_kwargs = mapping_functions["legacy_kwargs"] for legacy_key, new_key in legacy_kwargs.items(): if legacy_key in kwargs: kwargs[new_key] = kwargs.pop(le...
1,259
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_model.py
ctx = init_empty_weights if is_accelerate_available() else nullcontext with ctx(): model = cls.from_config(diffusers_model_config) # Check if `_keep_in_fp32_modules` is not None use_keep_in_fp32_modules = (cls._keep_in_fp32_modules is not None) and ( (torch_dtype == torc...
1,259
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_model.py
if is_accelerate_available(): param_device = torch.device(device) if device else torch.device("cpu") named_buffers = model.named_buffers() unexpected_keys = load_model_dict_into_meta( model, diffusers_format_checkpoint, dtype=torch_dtyp...
1,259
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_model.py
if len(unexpected_keys) > 0: logger.warning( f"Some weights of the model checkpoint were not used when initializing {cls.__name__}: \n {[', '.join(unexpected_keys)]}" ) if hf_quantizer is not None: hf_quantizer.postprocess_model(model) model.hf_qu...
1,259
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_model.py
class LoraBaseMixin: """Utility class for handling LoRAs.""" _lora_loadable_modules = [] num_fused_loras = 0 def load_lora_weights(self, **kwargs): raise NotImplementedError("`load_lora_weights()` is not implemented.") @classmethod def save_lora_weights(cls, **kwargs): raise N...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
Returns: tuple: A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True. """ return _func_optionally_disable_offloading(_pipeline=_pipeline) @classmethod def _fetch_state_dict(cls, *args, **kwargs): deprecation_message = f"Using th...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
@classmethod def _best_guess_weight_name(cls, *args, **kwargs): deprecation_message = f"Using the `_best_guess_weight_name()` method from {cls} has been deprecated and will be removed in a future version. Please use `from diffusers.loaders.lora_base import _best_guess_weight_name`." deprecate("_best...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
for component in self._lora_loadable_modules: model = getattr(self, component, None) if model is not None: if issubclass(model.__class__, ModelMixin): model.unload_lora() elif issubclass(model.__class__, PreTrainedModel): _r...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
Args: components: (`List[str]`): List of LoRA-injectable components to fuse the LoRAs into. lora_scale (`float`, defaults to 1.0): Controls how much to influence the outputs with the LoRA parameters. safe_fusing (`bool`, defaults to `False`): Whether t...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
pipeline = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16 ).to("cuda") pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel") pipeline.fuse_lora(lora_scale=0.7) ...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
depr_message = "Passing `fuse_transformer` to `fuse_lora()` is deprecated and will be ignored. Please use the `components` argument and provide a list of the components whose LoRAs are to be fused. `fuse_transformer` will be removed in a future version." deprecate( "fuse_transformer", ...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
if len(components) == 0: raise ValueError("`components` cannot be an empty list.") for fuse_component in components: if fuse_component not in self._lora_loadable_modules: raise ValueError(f"{fuse_component} is not found in {self._lora_loadable_modules=}.") m...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
def unfuse_lora(self, components: List[str] = [], **kwargs): r""" Reverses the effect of [`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraBaseMixin.fuse_lora). <Tip warning={true}> This is an experimental API. </Tip>
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
Args: components (`List[str]`): List of LoRA-injectable components to unfuse LoRA from. unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters. unfuse_text_encoder (`bool`, defaults to `True`): Whether to unfuse the text encoder LoRA para...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
depr_message = "Passing `unfuse_transformer` to `unfuse_lora()` is deprecated and will be ignored. Please use the `components` argument. `unfuse_transformer` will be removed in a future version." deprecate( "unfuse_transformer", "1.0.0", depr_message, ...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
if len(components) == 0: raise ValueError("`components` cannot be an empty list.") for fuse_component in components: if fuse_component not in self._lora_loadable_modules: raise ValueError(f"{fuse_component} is not found in {self._lora_loadable_modules=}.") m...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
# Expand weights into a list, one entry per adapter if not isinstance(adapter_weights, list): adapter_weights = [adapter_weights] * len(adapter_names) if len(adapter_names) != len(adapter_weights): raise ValueError( f"Length of adapter names {len(adapter_names)} ...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
# eg {"adapter1": ["unet"], "adapter2": ["unet", "text_encoder"]} invert_list_adapters = { adapter: [part for part, adapters in list_adapters.items() if adapter in adapters] for adapter in all_adapters } # Decompose weights into weights for denoiser and text encoders. ...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
if component_adapter_weights is not None and component not in invert_list_adapters[adapter_name]: logger.warning( ( f"Lora weight dict for adapter '{adapter_name}' contains {component}," f"but this will b...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
if issubclass(model.__class__, ModelMixin): model.set_adapters(adapter_names, _component_adapter_weights[component]) elif issubclass(model.__class__, PreTrainedModel): set_adapters_for_text_encoder(adapter_names, model, _component_adapter_weights[component]) def disable_...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
for component in self._lora_loadable_modules: model = getattr(self, component, None) if model is not None: if issubclass(model.__class__, ModelMixin): model.enable_lora() elif issubclass(model.__class__, PreTrainedModel): en...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
for component in self._lora_loadable_modules: model = getattr(self, component, None) if model is not None: if issubclass(model.__class__, ModelMixin): model.delete_adapters(adapter_names) elif issubclass(model.__class__, PreTrainedModel): ...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
pipeline = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", ).to("cuda") pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy") pipeline.get_active_adapters() ``` """ if not U...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
def get_list_adapters(self) -> Dict[str, List[str]]: """ Gets the current list of all available adapters in the pipeline. """ if not USE_PEFT_BACKEND: raise ValueError( "PEFT backend is required for this method. Please install the latest version of PEFT `pip i...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None: """ Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case you want to load multiple adapters and free some GPU memory. Args: ...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
for component in self._lora_loadable_modules: model = getattr(self, component, None) if model is not None: for module in model.modules(): if isinstance(module, BaseTunerLayer): for adapter_name in adapter_names: ...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
@staticmethod def pack_weights(layers, prefix): layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()} return layers_state_dict @staticmethod def ...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
os.makedirs(save_directory, exist_ok=True) if weight_name is None: if safe_serialization: weight_name = LORA_WEIGHT_NAME_SAFE else: weight_name = LORA_WEIGHT_NAME save_path = Path(save_directory, weight_name).as_posix() save_function(stat...
1,260
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_base.py
class SingleFileComponentError(Exception): def __init__(self, message=None): self.message = message super().__init__(self.message)
1,261
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/single_file_utils.py
class StableDiffusionLoraLoaderMixin(LoraBaseMixin): r""" Load LoRA layers into Stable Diffusion [`UNet2DConditionModel`] and [`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel). """ _lora_loadable_modules = ["unet", "text_encoder"] unet_name = ...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded into `self.text_encoder`.
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Parameters: pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`): See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`]. adapter_name (`str`, *optional*): Adapter name to be used for referencing the loaded adapter model. If not specif...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT_LORA) if low_cpu_mem_usage and not is_peft_version(">=", "0.13.1"): raise ValueError( "`low_cpu_mem_usage=True` is not compatible with this `peft` version. Please update it with `pip install -U peft`." ...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
self.load_lora_into_unet( state_dict, network_alphas=network_alphas, unet=getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet, adapter_name=adapter_name, _pipeline=self, low_cpu_mem_usage=low_cpu_mem_usage, ) s...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
<Tip warning={true}> We support loading A1111 formatted LoRA checkpoints in a limited capacity. This function is experimental and might change in the future. </Tip> Parameters: pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`): Can b...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
cache_dir (`Union[str, os.PathLike]`, *optional*): Path to a directory where a downloaded pretrained model configuration is cached if the standard cache is not used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force the (re-)dow...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
proxies (`Dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request. local_files_only (`bool`, *optional*, defaults to `False`): ...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
The subfolder location of a model file within a larger model repository on the Hub or locally. weight_name (`str`, *optional*, defaults to None): Name of the serialized state dict file. """ # Load the main state dict first which has the LoRA layers for either of # UNe...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
allow_pickle = False if use_safetensors is None: use_safetensors = True allow_pickle = True user_agent = { "file_type": "attn_procs_weights", "framework": "pytorch", }
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
state_dict = _fetch_state_dict( pretrained_model_name_or_path_or_dict=pretrained_model_name_or_path_or_dict, weight_name=weight_name, use_safetensors=use_safetensors, local_files_only=local_files_only, cache_dir=cache_dir, force_download=force_down...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
state_dict = {k: v for k, v in state_dict.items() if "dora_scale" not in k}
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
network_alphas = None # TODO: replace it with a method from `state_dict_utils` if all( ( k.startswith("lora_te_") or k.startswith("lora_unet_") or k.startswith("lora_te1_") or k.startswith("lora_te2_") ) ...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Parameters: state_dict (`dict`): A standard state dict containing the lora layer parameters. The keys can either be indexed directly into the unet or prefixed with an additional `unet` which can be used to distinguish between text encoder lora layers. ...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
`default_{i}` where i is the total number of adapters being loaded. low_cpu_mem_usage (`bool`, *optional*): Speed up model loading only loading the pretrained LoRA weights and not initializing the random weights. """ if not USE_PEFT_BACKEND: raise ...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
if low_cpu_mem_usage and not is_peft_version(">=", "0.13.1"): raise ValueError( "`low_cpu_mem_usage=True` is not compatible with this `peft` version. Please update it with `pip install -U peft`." )
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
# If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918), # then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as # their prefixes. keys = list(state_dict.keys()) only_text_encoder = all(key.startswith(cls....
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
@classmethod def load_lora_into_text_encoder( cls, state_dict, network_alphas, text_encoder, prefix=None, lora_scale=1.0, adapter_name=None, _pipeline=None, low_cpu_mem_usage=False, ): """ This will load the LoRA layers spec...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Parameters: state_dict (`dict`): A standard state dict containing the lora layer parameters. The key should be prefixed with an additional `text_encoder` to distinguish between unet lora layers. network_alphas (`Dict[str, float]`): The value of the...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
lora layer. adapter_name (`str`, *optional*): Adapter name to be used for referencing the loaded adapter model. If not specified, it will use `default_{i}` where i is the total number of adapters being loaded. low_cpu_mem_usage (`bool`, *optional*): ...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
@classmethod def save_lora_weights( cls, save_directory: Union[str, os.PathLike], unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None, text_encoder_lora_layers: Dict[str, torch.nn.Module] = None, is_main_process: bool = True, weight_name: str = No...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Arguments: save_directory (`str` or `os.PathLike`): Directory to save LoRA parameters to. Will be created if it doesn't exist. unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`): State dict of the LoRA layers corresponding to the `unet`. ...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
The function to use to save the state dictionary. Useful during distributed training when you need to replace `torch.save` with another method. Can be configured with the environment variable `DIFFUSERS_SAVE_MODE`. safe_serialization (`bool`, *optional*, defaults to `True`): ...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
if not (unet_lora_layers or text_encoder_lora_layers): raise ValueError("You must pass at least one of `unet_lora_layers` and `text_encoder_lora_layers`.") if unet_lora_layers: state_dict.update(cls.pack_weights(unet_lora_layers, cls.unet_name)) if text_encoder_lora_layers: ...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
def fuse_lora( self, components: List[str] = ["unet", "text_encoder"], lora_scale: float = 1.0, safe_fusing: bool = False, adapter_names: Optional[List[str]] = None, **kwargs, ): r""" Fuses the LoRA parameters into the original parameters of the corres...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Example: ```py from diffusers import DiffusionPipeline import torch pipeline = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16 ).to("cuda") pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Args: components (`List[str]`): List of LoRA-injectable components to unfuse LoRA from. unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters. unfuse_text_encoder (`bool`, defaults to `True`): Whether to unfuse the text encoder LoRA para...
1,262
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
class StableDiffusionXLLoraLoaderMixin(LoraBaseMixin): r""" Load LoRA layers into Stable Diffusion XL [`UNet2DConditionModel`], [`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), and [`CLIPTextModelWithProjection`](https://huggingface.co/docs/transform...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded. See [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into `self.unet`. See [`~loaders.StableDiffusionLoraLoa...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Parameters: pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`): See [`~loaders.StableDiffusionLoraLoaderMixin.lora_state_dict`]. adapter_name (`str`, *optional*): Adapter name to be used for referencing the loaded adapter model. If not specif...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT_LORA) if low_cpu_mem_usage and not is_peft_version(">=", "0.13.1"): raise ValueError( "`low_cpu_mem_usage=True` is not compatible with this `peft` version. Please update it with `pip install -U peft`." ...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
# First, ensure that the checkpoint is a compatible one and can be successfully loaded. state_dict, network_alphas = self.lora_state_dict( pretrained_model_name_or_path_or_dict, unet_config=self.unet.config, **kwargs, ) is_correct_format = all("lora" in key f...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
self.load_lora_into_unet( state_dict, network_alphas=network_alphas, unet=self.unet, adapter_name=adapter_name, _pipeline=self, low_cpu_mem_usage=low_cpu_mem_usage, ) text_encoder_state_dict = {k: v for k, v in state_dict.items() if...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k} if len(text_encoder_2_state_dict) > 0: self.load_lora_into_text_encoder( text_encoder_2_state_dict, network_alphas=network_alphas, text_encoder=self.text_encode...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
We support loading A1111 formatted LoRA checkpoints in a limited capacity. This function is experimental and might change in the future. </Tip> Parameters: pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`): Can be either: ...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
cache_dir (`Union[str, os.PathLike]`, *optional*): Path to a directory where a downloaded pretrained model configuration is cached if the standard cache is not used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force the (re-)dow...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
proxies (`Dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request. local_files_only (`bool`, *optional*, defaults to `False`): ...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
The subfolder location of a model file within a larger model repository on the Hub or locally. weight_name (`str`, *optional*, defaults to None): Name of the serialized state dict file. """ # Load the main state dict first which has the LoRA layers for either of # UNe...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
allow_pickle = False if use_safetensors is None: use_safetensors = True allow_pickle = True user_agent = { "file_type": "attn_procs_weights", "framework": "pytorch", }
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
state_dict = _fetch_state_dict( pretrained_model_name_or_path_or_dict=pretrained_model_name_or_path_or_dict, weight_name=weight_name, use_safetensors=use_safetensors, local_files_only=local_files_only, cache_dir=cache_dir, force_download=force_down...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
state_dict = {k: v for k, v in state_dict.items() if "dora_scale" not in k}
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
network_alphas = None # TODO: replace it with a method from `state_dict_utils` if all( ( k.startswith("lora_te_") or k.startswith("lora_unet_") or k.startswith("lora_te1_") or k.startswith("lora_te2_") ) ...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
@classmethod # Copied from diffusers.loaders.lora_pipeline.StableDiffusionLoraLoaderMixin.load_lora_into_unet def load_lora_into_unet( cls, state_dict, network_alphas, unet, adapter_name=None, _pipeline=None, low_cpu_mem_usage=False ): """ This will load the LoRA layers specified in ...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Parameters: state_dict (`dict`): A standard state dict containing the lora layer parameters. The keys can either be indexed directly into the unet or prefixed with an additional `unet` which can be used to distinguish between text encoder lora layers. ...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
`default_{i}` where i is the total number of adapters being loaded. low_cpu_mem_usage (`bool`, *optional*): Speed up model loading only loading the pretrained LoRA weights and not initializing the random weights. """ if not USE_PEFT_BACKEND: raise ...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
if low_cpu_mem_usage and not is_peft_version(">=", "0.13.1"): raise ValueError( "`low_cpu_mem_usage=True` is not compatible with this `peft` version. Please update it with `pip install -U peft`." )
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
# If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918), # then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as # their prefixes. keys = list(state_dict.keys()) only_text_encoder = all(key.startswith(cls....
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
@classmethod # Copied from diffusers.loaders.lora_pipeline.StableDiffusionLoraLoaderMixin.load_lora_into_text_encoder def load_lora_into_text_encoder( cls, state_dict, network_alphas, text_encoder, prefix=None, lora_scale=1.0, adapter_name=None, _p...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Parameters: state_dict (`dict`): A standard state dict containing the lora layer parameters. The key should be prefixed with an additional `text_encoder` to distinguish between unet lora layers. network_alphas (`Dict[str, float]`): The value of the...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
lora layer. adapter_name (`str`, *optional*): Adapter name to be used for referencing the loaded adapter model. If not specified, it will use `default_{i}` where i is the total number of adapters being loaded. low_cpu_mem_usage (`bool`, *optional*): ...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
@classmethod def save_lora_weights( cls, save_directory: Union[str, os.PathLike], unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None, text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None, text_encoder_2_lora_layers: Dict[str, ...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Arguments: save_directory (`str` or `os.PathLike`): Directory to save LoRA parameters to. Will be created if it doesn't exist. unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`): State dict of the LoRA layers corresponding to the `unet`. ...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Whether the process calling this is the main process or not. Useful during distributed training and you need to call this function on all processes. In this case, set `is_main_process=True` only on the main process to avoid race conditions. save_function (`Callable`): ...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers): raise ValueError( "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`." ) if unet_lora_layers: state_dict.update(cls...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
def fuse_lora( self, components: List[str] = ["unet", "text_encoder", "text_encoder_2"], lora_scale: float = 1.0, safe_fusing: bool = False, adapter_names: Optional[List[str]] = None, **kwargs, ): r""" Fuses the LoRA parameters into the original parame...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Args: components: (`List[str]`): List of LoRA-injectable components to fuse the LoRAs into. lora_scale (`float`, defaults to 1.0): Controls how much to influence the outputs with the LoRA parameters. safe_fusing (`bool`, defaults to `False`): Whether t...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
pipeline = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16 ).to("cuda") pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel") pipeline.fuse_lora(lora_scale=0.7) ...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
Args: components (`List[str]`): List of LoRA-injectable components to unfuse LoRA from. unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters. unfuse_text_encoder (`bool`, defaults to `True`): Whether to unfuse the text encoder LoRA para...
1,263
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
class SD3LoraLoaderMixin(LoraBaseMixin): r""" Load LoRA layers into [`SD3Transformer2DModel`], [`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), and [`CLIPTextModelWithProjection`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.C...
1,264
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
</Tip> Parameters: pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`): Can be either: - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on the Hub. - A...
1,264
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
cache_dir (`Union[str, os.PathLike]`, *optional*): Path to a directory where a downloaded pretrained model configuration is cached if the standard cache is not used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force the (re-)dow...
1,264
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
proxies (`Dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request. local_files_only (`bool`, *optional*, defaults to `False`): ...
1,264
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py
The subfolder location of a model file within a larger model repository on the Hub or locally.
1,264
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/loaders/lora_pipeline.py