text
stringlengths
1
1.02k
class_index
int64
0
1.38k
source
stringclasses
431 values
def validate_environment(self, *args, **kwargs): if not is_accelerate_available() or is_accelerate_version("<", "0.26.0"): raise ImportError( "Loading GGUF Parameters requires `accelerate` installed in your enviroment: `pip install 'accelerate>=0.26.0'`" ) if not is_gguf_available() or is_gguf_version("<", "0.10.0"): raise ImportError( "To load GGUF format files you must have `gguf` installed in your environment: `pip install gguf>=0.10.0`" ) # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.adjust_max_memory def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]: # need more space for buffers that are created during quantization max_memory = {key: val * 0.90 for key, val in max_memory.items()} return max_memory
24
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/gguf/gguf_quantizer.py
def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype": if target_dtype != torch.uint8: logger.info(f"target_dtype {target_dtype} is replaced by `torch.uint8` for GGUF quantization") return torch.uint8 def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype": if torch_dtype is None: torch_dtype = self.compute_dtype return torch_dtype def check_quantized_param_shape(self, param_name, current_param, loaded_param): loaded_param_shape = loaded_param.shape current_param_shape = current_param.shape quant_type = loaded_param.quant_type block_size, type_size = GGML_QUANT_SIZES[quant_type]
24
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/gguf/gguf_quantizer.py
inferred_shape = _quant_shape_from_byte_shape(loaded_param_shape, type_size, block_size) if inferred_shape != current_param_shape: raise ValueError( f"{param_name} has an expected quantized shape of: {inferred_shape}, but receieved shape: {loaded_param_shape}" ) return True def check_if_quantized_param( self, model: "ModelMixin", param_value: Union["GGUFParameter", "torch.Tensor"], param_name: str, state_dict: Dict[str, Any], **kwargs, ) -> bool: if isinstance(param_value, GGUFParameter): return True return False
24
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/gguf/gguf_quantizer.py
def create_quantized_param( self, model: "ModelMixin", param_value: Union["GGUFParameter", "torch.Tensor"], param_name: str, target_device: "torch.device", state_dict: Optional[Dict[str, Any]] = None, unexpected_keys: Optional[List[str]] = None, ): module, tensor_name = get_module_from_name(model, param_name) if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.") if tensor_name in module._parameters: module._parameters[tensor_name] = param_value.to(target_device) if tensor_name in module._buffers: module._buffers[tensor_name] = param_value.to(target_device)
24
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/gguf/gguf_quantizer.py
def _process_model_before_weight_loading( self, model: "ModelMixin", device_map, keep_in_fp32_modules: List[str] = [], **kwargs, ): state_dict = kwargs.get("state_dict", None) self.modules_to_not_convert.extend(keep_in_fp32_modules) self.modules_to_not_convert = [module for module in self.modules_to_not_convert if module is not None] _replace_with_gguf_linear( model, self.compute_dtype, state_dict, modules_to_not_convert=self.modules_to_not_convert ) def _process_model_after_weight_loading(self, model: "ModelMixin", **kwargs): return model @property def is_serializable(self): return False @property def is_trainable(self) -> bool: return False
24
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/gguf/gguf_quantizer.py
def _dequantize(self, model): is_model_on_cpu = model.device.type == "cpu" if is_model_on_cpu: logger.info( "Model was found to be on CPU (could happen as a result of `enable_model_cpu_offload()`). So, moving it to GPU. After dequantization, will move the model back to CPU again to preserve the previous device." ) model.to(torch.cuda.current_device()) model = _dequantize_gguf_and_restore_linear(model, self.modules_to_not_convert) if is_model_on_cpu: model.to("cpu") return model
24
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/gguf/gguf_quantizer.py
class GGUFParameter(torch.nn.Parameter): def __new__(cls, data, requires_grad=False, quant_type=None): data = data if data is not None else torch.empty(0) self = torch.Tensor._make_subclass(cls, data, requires_grad) self.quant_type = quant_type return self def as_tensor(self): return torch.Tensor._make_subclass(torch.Tensor, self, self.requires_grad) @classmethod def __torch_function__(cls, func, types, args=(), kwargs=None): if kwargs is None: kwargs = {} result = super().__torch_function__(func, types, args, kwargs)
25
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/gguf/utils.py
# When converting from original format checkpoints we often use splits, cats etc on tensors # this method ensures that the returned tensor type from those operations remains GGUFParameter # so that we preserve quant_type information quant_type = None for arg in args: if isinstance(arg, list) and (arg[0], GGUFParameter): quant_type = arg[0].quant_type break if isinstance(arg, GGUFParameter): quant_type = arg.quant_type break if isinstance(result, torch.Tensor): return cls(result, quant_type=quant_type) # Handle tuples and lists elif isinstance(result, (tuple, list)): # Preserve the original type (tuple or list) wrapped = [cls(x, quant_type=quant_type) if isinstance(x, torch.Tensor) else x for x in result] return type(result)(wrapped) else: return result
25
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/gguf/utils.py
class GGUFLinear(nn.Linear): def __init__( self, in_features, out_features, bias=False, compute_dtype=None, device=None, ) -> None: super().__init__(in_features, out_features, bias, device) self.compute_dtype = compute_dtype def forward(self, inputs): weight = dequantize_gguf_tensor(self.weight) weight = weight.to(self.compute_dtype) bias = self.bias.to(self.compute_dtype) if self.bias is not None else None output = torch.nn.functional.linear(inputs, weight, bias) return output
26
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/gguf/utils.py
class TorchAoHfQuantizer(DiffusersQuantizer): r""" Diffusers Quantizer for TorchAO: https://github.com/pytorch/ao/. """ requires_calibration = False required_packages = ["torchao"] def __init__(self, quantization_config, **kwargs): super().__init__(quantization_config, **kwargs) def validate_environment(self, *args, **kwargs): if not is_torchao_available(): raise ImportError( "Loading a TorchAO quantized model requires the torchao library. Please install with `pip install torchao`" ) torchao_version = version.parse(importlib.metadata.version("torch")) if torchao_version < version.parse("0.7.0"): raise RuntimeError( f"The minimum required version of `torchao` is 0.7.0, but the current version is {torchao_version}. Please upgrade with `pip install -U torchao`." ) self.offload = False
27
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/torchao/torchao_quantizer.py
device_map = kwargs.get("device_map", None) if isinstance(device_map, dict): if "cpu" in device_map.values() or "disk" in device_map.values(): if self.pre_quantized: raise ValueError( "You are attempting to perform cpu/disk offload with a pre-quantized torchao model " "This is not supported yet. Please remove the CPU or disk device from the `device_map` argument." ) else: self.offload = True
27
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/torchao/torchao_quantizer.py
if self.pre_quantized: weights_only = kwargs.get("weights_only", None) if weights_only: torch_version = version.parse(importlib.metadata.version("torch")) if torch_version < version.parse("2.5.0"): # TODO(aryan): TorchAO is compatible with Pytorch >= 2.2 for certain quantization types. Try to see if we can support it in future raise RuntimeError( f"In order to use TorchAO pre-quantized model, you need to have torch>=2.5.0. However, the current version is {torch_version}." ) def update_torch_dtype(self, torch_dtype): quant_type = self.quantization_config.quant_type
27
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/torchao/torchao_quantizer.py
if quant_type.startswith("int") or quant_type.startswith("uint"): if torch_dtype is not None and torch_dtype != torch.bfloat16: logger.warning( f"You are trying to set torch_dtype to {torch_dtype} for int4/int8/uintx quantization, but " f"only bfloat16 is supported right now. Please set `torch_dtype=torch.bfloat16`." ) if torch_dtype is None: # We need to set the torch_dtype, otherwise we have dtype mismatch when performing the quantized linear op logger.warning( "Overriding `torch_dtype` with `torch_dtype=torch.bfloat16` due to requirements of `torchao` " "to enable model loading in different precisions. Pass your own `torch_dtype` to specify the " "dtype of the remaining non-linear layers, or pass torch_dtype=torch.bfloat16, to remove this warning." ) torch_dtype = torch.bfloat16 return torch_dtype
27
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/torchao/torchao_quantizer.py
def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype": quant_type = self.quantization_config.quant_type if quant_type.startswith("int8") or quant_type.startswith("int4"): # Note that int4 weights are created by packing into torch.int8, but since there is no torch.int4, we use torch.int8 return torch.int8 elif quant_type == "uintx_weight_only": return self.quantization_config.quant_type_kwargs.get("dtype", torch.uint8) elif quant_type.startswith("uint"): return { 1: torch.uint1, 2: torch.uint2, 3: torch.uint3, 4: torch.uint4, 5: torch.uint5, 6: torch.uint6, 7: torch.uint7, }[int(quant_type[4])] elif quant_type.startswith("float") or quant_type.startswith("fp"): return torch.bfloat16
27
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/torchao/torchao_quantizer.py
if isinstance(target_dtype, SUPPORTED_TORCH_DTYPES_FOR_QUANTIZATION): return target_dtype # We need one of the supported dtypes to be selected in order for accelerate to determine # the total size of modules/parameters for auto device placement. possible_device_maps = ["auto", "balanced", "balanced_low_0", "sequential"] raise ValueError( f"You have set `device_map` as one of {possible_device_maps} on a TorchAO quantized model but a suitable target dtype " f"could not be inferred. The supported target_dtypes are: {SUPPORTED_TORCH_DTYPES_FOR_QUANTIZATION}. If you think the " f"dtype you are using should be supported, please open an issue at https://github.com/huggingface/diffusers/issues." ) def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]: max_memory = {key: val * 0.9 for key, val in max_memory.items()} return max_memory
27
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/torchao/torchao_quantizer.py
def check_if_quantized_param( self, model: "ModelMixin", param_value: "torch.Tensor", param_name: str, state_dict: Dict[str, Any], **kwargs, ) -> bool: param_device = kwargs.pop("param_device", None) # Check if the param_name is not in self.modules_to_not_convert if any((key + "." in param_name) or (key == param_name) for key in self.modules_to_not_convert): return False elif param_device == "cpu" and self.offload: # We don't quantize weights that we offload return False else: # We only quantize the weight of nn.Linear module, tensor_name = get_module_from_name(model, param_name) return isinstance(module, torch.nn.Linear) and (tensor_name == "weight")
27
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/torchao/torchao_quantizer.py
def create_quantized_param( self, model: "ModelMixin", param_value: "torch.Tensor", param_name: str, target_device: "torch.device", state_dict: Dict[str, Any], unexpected_keys: List[str], ): r""" Each nn.Linear layer that needs to be quantized is processsed here. First, we set the value the weight tensor, then we move it to the target device. Finally, we quantize the module. """ module, tensor_name = get_module_from_name(model, param_name)
27
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/torchao/torchao_quantizer.py
if self.pre_quantized: # If we're loading pre-quantized weights, replace the repr of linear layers for pretty printing info # about AffineQuantizedTensor module._parameters[tensor_name] = torch.nn.Parameter(param_value.to(device=target_device)) if isinstance(module, nn.Linear): module.extra_repr = types.MethodType(_linear_extra_repr, module) else: # As we perform quantization here, the repr of linear layers is that of AQT, so we don't have to do it ourselves module._parameters[tensor_name] = torch.nn.Parameter(param_value).to(device=target_device) quantize_(module, self.quantization_config.get_apply_tensor_subclass()) def _process_model_before_weight_loading( self, model: "ModelMixin", device_map, keep_in_fp32_modules: List[str] = [], **kwargs, ): self.modules_to_not_convert = self.quantization_config.modules_to_not_convert
27
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/torchao/torchao_quantizer.py
if not isinstance(self.modules_to_not_convert, list): self.modules_to_not_convert = [self.modules_to_not_convert] self.modules_to_not_convert.extend(keep_in_fp32_modules) # Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk` if isinstance(device_map, dict) and len(device_map.keys()) > 1: keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]] self.modules_to_not_convert.extend(keys_on_cpu) # Purge `None`. # Unlike `transformers`, we don't know if we should always keep certain modules in FP32 # in case of diffusion transformer models. For language models and others alike, `lm_head` # and tied modules are usually kept in FP32. self.modules_to_not_convert = [module for module in self.modules_to_not_convert if module is not None] model.config.quantization_config = self.quantization_config
27
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/torchao/torchao_quantizer.py
def _process_model_after_weight_loading(self, model: "ModelMixin"): return model def is_serializable(self, safe_serialization=None): # TODO(aryan): needs to be tested if safe_serialization: logger.warning( "torchao quantized model does not support safe serialization, please set `safe_serialization` to False." ) return False _is_torchao_serializable = version.parse(importlib.metadata.version("huggingface_hub")) >= version.parse( "0.25.0" ) if not _is_torchao_serializable: logger.warning("torchao quantized model is only serializable after huggingface_hub >= 0.25.0 ")
27
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/torchao/torchao_quantizer.py
if self.offload and self.quantization_config.modules_to_not_convert is None: logger.warning( "The model contains offloaded modules and these modules are not quantized. We don't recommend saving the model as we won't be able to reload them." "If you want to specify modules to not quantize, please specify modules_to_not_convert in the quantization_config." ) return False return _is_torchao_serializable @property def is_trainable(self): return self.quantization_config.quant_type.startswith("int8")
27
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/torchao/torchao_quantizer.py
class BnB4BitDiffusersQuantizer(DiffusersQuantizer): """ 4-bit quantization from bitsandbytes.py quantization method: before loading: converts transformer layers into Linear4bit during loading: load 16bit weight and pass to the layer object after: quantizes individual weights in Linear4bit into 4bit at the first .cuda() call saving: from state dict, as usual; saves weights and `quant_state` components loading: need to locate `quant_state` components and pass to Param4bit constructor """ use_keep_in_fp32_modules = True requires_calibration = False def __init__(self, quantization_config, **kwargs): super().__init__(quantization_config, **kwargs) if self.quantization_config.llm_int8_skip_modules is not None: self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
def validate_environment(self, *args, **kwargs): if not torch.cuda.is_available(): raise RuntimeError("No GPU found. A GPU is needed for quantization.") if not is_accelerate_available() or is_accelerate_version("<", "0.26.0"): raise ImportError( "Using `bitsandbytes` 4-bit quantization requires Accelerate: `pip install 'accelerate>=0.26.0'`" ) if not is_bitsandbytes_available() or is_bitsandbytes_version("<", "0.43.3"): raise ImportError( "Using `bitsandbytes` 4-bit quantization requires the latest version of bitsandbytes: `pip install -U bitsandbytes`" ) if kwargs.get("from_flax", False): raise ValueError( "Converting into 4-bit weights from flax weights is currently not supported, please make" " sure the weights are in PyTorch format." )
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
device_map = kwargs.get("device_map", None) if ( device_map is not None and isinstance(device_map, dict) and not self.quantization_config.llm_int8_enable_fp32_cpu_offload ): device_map_without_no_convert = { key: device_map[key] for key in device_map.keys() if key not in self.modules_to_not_convert } if "cpu" in device_map_without_no_convert.values() or "disk" in device_map_without_no_convert.values(): raise ValueError( "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the " "quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules " "in 32-bit, you need to set `load_in_8bit_fp32_cpu_offload=True` and pass a custom `device_map` to " "`from_pretrained`. Check "
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
"https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu " "for more details. " )
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype": if target_dtype != torch.int8: from accelerate.utils import CustomDtype logger.info("target_dtype {target_dtype} is replaced by `CustomDtype.INT4` for 4-bit BnB quantization") return CustomDtype.INT4 else: raise ValueError(f"Wrong `target_dtype` ({target_dtype}) provided.") def check_if_quantized_param( self, model: "ModelMixin", param_value: "torch.Tensor", param_name: str, state_dict: Dict[str, Any], **kwargs, ) -> bool: import bitsandbytes as bnb
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
module, tensor_name = get_module_from_name(model, param_name) if isinstance(module._parameters.get(tensor_name, None), bnb.nn.Params4bit): # Add here check for loaded components' dtypes once serialization is implemented return True elif isinstance(module, bnb.nn.Linear4bit) and tensor_name == "bias": # bias could be loaded by regular set_module_tensor_to_device() from accelerate, # but it would wrongly use uninitialized weight there. return True else: return False def create_quantized_param( self, model: "ModelMixin", param_value: "torch.Tensor", param_name: str, target_device: "torch.device", state_dict: Dict[str, Any], unexpected_keys: Optional[List[str]] = None, ): import bitsandbytes as bnb module, tensor_name = get_module_from_name(model, param_name)
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
if tensor_name not in module._parameters: raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.") old_value = getattr(module, tensor_name) if tensor_name == "bias": if param_value is None: new_value = old_value.to(target_device) else: new_value = param_value.to(target_device) new_value = torch.nn.Parameter(new_value, requires_grad=old_value.requires_grad) module._parameters[tensor_name] = new_value return
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
if not isinstance(module._parameters[tensor_name], bnb.nn.Params4bit): raise ValueError("this function only loads `Linear4bit components`") if ( old_value.device == torch.device("meta") and target_device not in ["meta", torch.device("meta")] and param_value is None ): raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {target_device}.") # construct `new_value` for the module._parameters[tensor_name]: if self.pre_quantized: # 4bit loading. Collecting components for restoring quantized weight # This can be expanded to make a universal call for any quantized weight loading
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
if not self.is_serializable: raise ValueError( "Detected int4 weights but the version of bitsandbytes is not compatible with int4 serialization. " "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`." ) if (param_name + ".quant_state.bitsandbytes__fp4" not in state_dict) and ( param_name + ".quant_state.bitsandbytes__nf4" not in state_dict ): raise ValueError( f"Supplied state dict for {param_name} does not contain `bitsandbytes__*` and possibly other `quantized_stats` components." )
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
quantized_stats = {} for k, v in state_dict.items(): # `startswith` to counter for edge cases where `param_name` # substring can be present in multiple places in the `state_dict` if param_name + "." in k and k.startswith(param_name): quantized_stats[k] = v if unexpected_keys is not None and k in unexpected_keys: unexpected_keys.remove(k) new_value = bnb.nn.Params4bit.from_prequantized( data=param_value, quantized_stats=quantized_stats, requires_grad=False, device=target_device, ) else: new_value = param_value.to("cpu") kwargs = old_value.__dict__ new_value = bnb.nn.Params4bit(new_value, requires_grad=False, **kwargs).to(target_device) module._parameters[tensor_name] = new_value
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
def check_quantized_param_shape(self, param_name, current_param, loaded_param): current_param_shape = current_param.shape loaded_param_shape = loaded_param.shape n = current_param_shape.numel() inferred_shape = (n,) if "bias" in param_name else ((n + 1) // 2, 1) if loaded_param_shape != inferred_shape: raise ValueError( f"Expected the flattened shape of the current param ({param_name}) to be {loaded_param_shape} but is {inferred_shape}." ) else: return True def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]: # need more space for buffers that are created during quantization max_memory = {key: val * 0.90 for key, val in max_memory.items()} return max_memory
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype": if torch_dtype is None: # We force the `dtype` to be float16, this is a requirement from `bitsandbytes` logger.info( "Overriding torch_dtype=%s with `torch_dtype=torch.float16` due to " "requirements of `bitsandbytes` to enable model loading in 8-bit or 4-bit. " "Pass your own torch_dtype to specify the dtype of the remaining non-linear layers or pass" " torch_dtype=torch.float16 to remove this warning.", torch_dtype, ) torch_dtype = torch.float16 return torch_dtype
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
# (sayakpaul): I think it could be better to disable custom `device_map`s # for the first phase of the integration in the interest of simplicity. # Commenting this for discussions on the PR. # def update_device_map(self, device_map): # if device_map is None: # device_map = {"": torch.cuda.current_device()} # logger.info( # "The device_map was not initialized. " # "Setting device_map to {'':torch.cuda.current_device()}. " # "If you want to use the model for inference, please set device_map ='auto' " # ) # return device_map def _process_model_before_weight_loading( self, model: "ModelMixin", device_map, keep_in_fp32_modules: List[str] = [], **kwargs, ): from .utils import replace_with_bnb_linear load_in_8bit_fp32_cpu_offload = self.quantization_config.llm_int8_enable_fp32_cpu_offload
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
# We may keep some modules such as the `proj_out` in their original dtype for numerical stability reasons self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules if not isinstance(self.modules_to_not_convert, list): self.modules_to_not_convert = [self.modules_to_not_convert] self.modules_to_not_convert.extend(keep_in_fp32_modules) # Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk` if isinstance(device_map, dict) and len(device_map.keys()) > 1: keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
if len(keys_on_cpu) > 0 and not load_in_8bit_fp32_cpu_offload: raise ValueError( "If you want to offload some keys to `cpu` or `disk`, you need to set " "`llm_int8_enable_fp32_cpu_offload=True`. Note that these modules will not be " " converted to 8-bit but kept in 32-bit." ) self.modules_to_not_convert.extend(keys_on_cpu) # Purge `None`. # Unlike `transformers`, we don't know if we should always keep certain modules in FP32 # in case of diffusion transformer models. For language models and others alike, `lm_head` # and tied modules are usually kept in FP32. self.modules_to_not_convert = [module for module in self.modules_to_not_convert if module is not None]
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
model = replace_with_bnb_linear( model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config ) model.config.quantization_config = self.quantization_config def _process_model_after_weight_loading(self, model: "ModelMixin", **kwargs): model.is_loaded_in_4bit = True model.is_4bit_serializable = self.is_serializable return model @property def is_serializable(self): # Because we're mandating `bitsandbytes` 0.43.3. return True @property def is_trainable(self) -> bool: # Because we're mandating `bitsandbytes` 0.43.3. return True def _dequantize(self, model): from .utils import dequantize_and_replace
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
is_model_on_cpu = model.device.type == "cpu" if is_model_on_cpu: logger.info( "Model was found to be on CPU (could happen as a result of `enable_model_cpu_offload()`). So, moving it to GPU. After dequantization, will move the model back to CPU again to preserve the previous device." ) model.to(torch.cuda.current_device()) model = dequantize_and_replace( model, self.modules_to_not_convert, quantization_config=self.quantization_config ) if is_model_on_cpu: model.to("cpu") return model
28
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
class BnB8BitDiffusersQuantizer(DiffusersQuantizer): """ 8-bit quantization from bitsandbytes quantization method: before loading: converts transformer layers into Linear8bitLt during loading: load 16bit weight and pass to the layer object after: quantizes individual weights in Linear8bitLt into 8bit at fitst .cuda() call saving: from state dict, as usual; saves weights and 'SCB' component loading: need to locate SCB component and pass to the Linear8bitLt object """ use_keep_in_fp32_modules = True requires_calibration = False def __init__(self, quantization_config, **kwargs): super().__init__(quantization_config, **kwargs) if self.quantization_config.llm_int8_skip_modules is not None: self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
def validate_environment(self, *args, **kwargs): if not torch.cuda.is_available(): raise RuntimeError("No GPU found. A GPU is needed for quantization.") if not is_accelerate_available() or is_accelerate_version("<", "0.26.0"): raise ImportError( "Using `bitsandbytes` 8-bit quantization requires Accelerate: `pip install 'accelerate>=0.26.0'`" ) if not is_bitsandbytes_available() or is_bitsandbytes_version("<", "0.43.3"): raise ImportError( "Using `bitsandbytes` 8-bit quantization requires the latest version of bitsandbytes: `pip install -U bitsandbytes`" ) if kwargs.get("from_flax", False): raise ValueError( "Converting into 8-bit weights from flax weights is currently not supported, please make" " sure the weights are in PyTorch format." )
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
device_map = kwargs.get("device_map", None) if ( device_map is not None and isinstance(device_map, dict) and not self.quantization_config.llm_int8_enable_fp32_cpu_offload ): device_map_without_no_convert = { key: device_map[key] for key in device_map.keys() if key not in self.modules_to_not_convert } if "cpu" in device_map_without_no_convert.values() or "disk" in device_map_without_no_convert.values(): raise ValueError( "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the " "quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules " "in 32-bit, you need to set `load_in_8bit_fp32_cpu_offload=True` and pass a custom `device_map` to " "`from_pretrained`. Check "
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
"https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu " "for more details. " )
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
# Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.adjust_max_memory def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]: # need more space for buffers that are created during quantization max_memory = {key: val * 0.90 for key, val in max_memory.items()} return max_memory
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
# Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.update_torch_dtype def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype": if torch_dtype is None: # We force the `dtype` to be float16, this is a requirement from `bitsandbytes` logger.info( "Overriding torch_dtype=%s with `torch_dtype=torch.float16` due to " "requirements of `bitsandbytes` to enable model loading in 8-bit or 4-bit. " "Pass your own torch_dtype to specify the dtype of the remaining non-linear layers or pass" " torch_dtype=torch.float16 to remove this warning.", torch_dtype, ) torch_dtype = torch.float16 return torch_dtype
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
# # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.update_device_map # def update_device_map(self, device_map): # if device_map is None: # device_map = {"": torch.cuda.current_device()} # logger.info( # "The device_map was not initialized. " # "Setting device_map to {'':torch.cuda.current_device()}. " # "If you want to use the model for inference, please set device_map ='auto' " # ) # return device_map def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype": if target_dtype != torch.int8: logger.info("target_dtype {target_dtype} is replaced by `torch.int8` for 8-bit BnB quantization") return torch.int8
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
def check_if_quantized_param( self, model: "ModelMixin", param_value: "torch.Tensor", param_name: str, state_dict: Dict[str, Any], **kwargs, ): import bitsandbytes as bnb module, tensor_name = get_module_from_name(model, param_name) if isinstance(module._parameters.get(tensor_name, None), bnb.nn.Int8Params): if self.pre_quantized: if param_name.replace("weight", "SCB") not in state_dict.keys(): raise ValueError("Missing quantization component `SCB`") if param_value.dtype != torch.int8: raise ValueError( f"Incompatible dtype `{param_value.dtype}` when loading 8-bit prequantized weight. Expected `torch.int8`." ) return True return False
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
def create_quantized_param( self, model: "ModelMixin", param_value: "torch.Tensor", param_name: str, target_device: "torch.device", state_dict: Dict[str, Any], unexpected_keys: Optional[List[str]] = None, ): import bitsandbytes as bnb fp16_statistics_key = param_name.replace("weight", "SCB") fp16_weights_format_key = param_name.replace("weight", "weight_format") fp16_statistics = state_dict.get(fp16_statistics_key, None) fp16_weights_format = state_dict.get(fp16_weights_format_key, None) module, tensor_name = get_module_from_name(model, param_name) if tensor_name not in module._parameters: raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.") old_value = getattr(module, tensor_name)
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
if not isinstance(module._parameters[tensor_name], bnb.nn.Int8Params): raise ValueError(f"Parameter `{tensor_name}` should only be a `bnb.nn.Int8Params` instance.") if ( old_value.device == torch.device("meta") and target_device not in ["meta", torch.device("meta")] and param_value is None ): raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {target_device}.") new_value = param_value.to("cpu") if self.pre_quantized and not self.is_serializable: raise ValueError( "Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. " "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`." ) kwargs = old_value.__dict__ new_value = bnb.nn.Int8Params(new_value, requires_grad=False, **kwargs).to(target_device)
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
module._parameters[tensor_name] = new_value if fp16_statistics is not None: setattr(module.weight, "SCB", fp16_statistics.to(target_device)) if unexpected_keys is not None: unexpected_keys.remove(fp16_statistics_key) # We just need to pop the `weight_format` keys from the state dict to remove unneeded # messages. The correct format is correctly retrieved during the first forward pass. if fp16_weights_format is not None and unexpected_keys is not None: unexpected_keys.remove(fp16_weights_format_key) # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer._process_model_after_weight_loading with 4bit->8bit def _process_model_after_weight_loading(self, model: "ModelMixin", **kwargs): model.is_loaded_in_8bit = True model.is_8bit_serializable = self.is_serializable return model
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
# Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer._process_model_before_weight_loading def _process_model_before_weight_loading( self, model: "ModelMixin", device_map, keep_in_fp32_modules: List[str] = [], **kwargs, ): from .utils import replace_with_bnb_linear load_in_8bit_fp32_cpu_offload = self.quantization_config.llm_int8_enable_fp32_cpu_offload # We may keep some modules such as the `proj_out` in their original dtype for numerical stability reasons self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules if not isinstance(self.modules_to_not_convert, list): self.modules_to_not_convert = [self.modules_to_not_convert] self.modules_to_not_convert.extend(keep_in_fp32_modules)
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
# Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk` if isinstance(device_map, dict) and len(device_map.keys()) > 1: keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]] if len(keys_on_cpu) > 0 and not load_in_8bit_fp32_cpu_offload: raise ValueError( "If you want to offload some keys to `cpu` or `disk`, you need to set " "`llm_int8_enable_fp32_cpu_offload=True`. Note that these modules will not be " " converted to 8-bit but kept in 32-bit." ) self.modules_to_not_convert.extend(keys_on_cpu)
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
# Purge `None`. # Unlike `transformers`, we don't know if we should always keep certain modules in FP32 # in case of diffusion transformer models. For language models and others alike, `lm_head` # and tied modules are usually kept in FP32. self.modules_to_not_convert = [module for module in self.modules_to_not_convert if module is not None] model = replace_with_bnb_linear( model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config ) model.config.quantization_config = self.quantization_config @property # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.is_serializable def is_serializable(self): # Because we're mandating `bitsandbytes` 0.43.3. return True
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
@property # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.is_serializable def is_trainable(self) -> bool: # Because we're mandating `bitsandbytes` 0.43.3. return True def _dequantize(self, model): from .utils import dequantize_and_replace model = dequantize_and_replace( model, self.modules_to_not_convert, quantization_config=self.quantization_config ) return model
29
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/bitsandbytes/bnb_quantizer.py
class FlaxImagePipelineOutput(BaseOutput): """ Output class for image pipelines. Args: images (`List[PIL.Image.Image]` or `np.ndarray`) List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width, num_channels)`. """ images: Union[List[PIL.Image.Image], np.ndarray]
30
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
class FlaxDiffusionPipeline(ConfigMixin, PushToHubMixin): r""" Base class for Flax-based pipelines. [`FlaxDiffusionPipeline`] stores all components (models, schedulers, and processors) for diffusion pipelines and provides methods for loading, downloading and saving models. It also includes methods to: - enable/disable the progress bar for the denoising iteration Class attributes: - **config_name** ([`str`]) -- The configuration filename that stores the class and module names of all the diffusion pipeline's components. """ config_name = "model_index.json" def register_modules(self, **kwargs): # import it here to avoid circular import from diffusers import pipelines for name, module in kwargs.items(): if module is None: register_dict = {name: (None, None)} else: # retrieve library library = module.__module__.split(".")[0]
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
# check if the module is a pipeline module pipeline_dir = module.__module__.split(".")[-2] path = module.__module__.split(".") is_pipeline_module = pipeline_dir in path and hasattr(pipelines, pipeline_dir) # if library is not in LOADABLE_CLASSES, then it is a custom module. # Or if it's a pipeline module, then the module is inside the pipeline # folder so we set the library to module name. if library not in LOADABLE_CLASSES or is_pipeline_module: library = pipeline_dir # retrieve class_name class_name = module.__class__.__name__ register_dict = {name: (library, class_name)} # save model index config self.register_to_config(**register_dict) # set models setattr(self, name, module)
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
def save_pretrained( self, save_directory: Union[str, os.PathLike], params: Union[Dict, FrozenDict], push_to_hub: bool = False, **kwargs, ): # TODO: handle inference_state """ Save all saveable variables of the pipeline to a directory. A pipeline variable can be saved and loaded if its class implements both a save and loading method. The pipeline is easily reloaded using the [`~FlaxDiffusionPipeline.from_pretrained`] class method.
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
Arguments: save_directory (`str` or `os.PathLike`): Directory to which to save. Will be created if it doesn't exist. push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace). kwargs (`Dict[str, Any]`, *optional*): Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method. """ self.save_config(save_directory) model_index_dict = dict(self.config) model_index_dict.pop("_class_name") model_index_dict.pop("_diffusers_version") model_index_dict.pop("_module", None)
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
if push_to_hub: commit_message = kwargs.pop("commit_message", None) private = kwargs.pop("private", None) create_pr = kwargs.pop("create_pr", False) token = kwargs.pop("token", None) repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1]) repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id for pipeline_component_name in model_index_dict.keys(): sub_model = getattr(self, pipeline_component_name) if sub_model is None: # edge case for saving a pipeline with safety_checker=None continue model_cls = sub_model.__class__
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
save_method_name = None # search for the model's base class in LOADABLE_CLASSES for library_name, library_classes in LOADABLE_CLASSES.items(): library = importlib.import_module(library_name) for base_class, save_load_methods in library_classes.items(): class_candidate = getattr(library, base_class, None) if class_candidate is not None and issubclass(model_cls, class_candidate): # if we found a suitable base class in LOADABLE_CLASSES then grab its save method save_method_name = save_load_methods[0] break if save_method_name is not None: break save_method = getattr(sub_model, save_method_name) expects_params = "params" in set(inspect.signature(save_method).parameters.keys())
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
if expects_params: save_method( os.path.join(save_directory, pipeline_component_name), params=params[pipeline_component_name] ) else: save_method(os.path.join(save_directory, pipeline_component_name)) if push_to_hub: self._upload_folder( save_directory, repo_id, token=token, commit_message=commit_message, create_pr=create_pr, ) @classmethod @validate_hf_hub_args def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs): r""" Instantiate a Flax-based diffusion pipeline from pretrained pipeline weights. The pipeline is set in evaluation mode (`model.eval()) by default and dropout modules are deactivated.
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
If you get the error message below, you need to finetune the weights for your downstream task: ``` Some weights of FlaxUNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match: ``` Parameters: pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*): Can be either:
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
- A string, the *repo id* (for example `stable-diffusion-v1-5/stable-diffusion-v1-5`) of a pretrained pipeline hosted on the Hub. - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved using [`~FlaxDiffusionPipeline.save_pretrained`]. dtype (`str` or `jnp.dtype`, *optional*): Override the default `jnp.dtype` and load the model under this dtype. If `"auto"`, the dtype is automatically derived from the model's weights. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist.
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.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. output_loading_info(`bool`, *optional*, defaults to `False`): Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages. local_files_only (`bool`, *optional*, defaults to `False`): Whether to only load local model weights and configuration files or not. If set to `True`, the model won't be downloaded from the Hub. token (`str` or *bool*, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from `diffusers-cli login` (stored in `~/.huggingface`) is used. revision (`str`, *optional*, defaults to `"main"`):
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier allowed by Git. mirror (`str`, *optional*): Mirror source to resolve accessibility issues if you're downloading a model in China. We do not guarantee the timeliness or safety of the source, and you should refer to the mirror site for more information. kwargs (remaining dictionary of keyword arguments, *optional*): Can be used to overwrite load and saveable variables (the pipeline components) of the specific pipeline class. The overwritten components are passed directly to the pipelines `__init__` method.
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
<Tip> To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in with `huggingface-cli login`. </Tip> Examples: ```py >>> from diffusers import FlaxDiffusionPipeline >>> # Download pipeline from huggingface.co and cache. >>> # Requires to be logged in to Hugging Face hub, >>> # see more in [the documentation](https://huggingface.co/docs/hub/security-tokens) >>> pipeline, params = FlaxDiffusionPipeline.from_pretrained( ... "stable-diffusion-v1-5/stable-diffusion-v1-5", ... variant="bf16", ... dtype=jnp.bfloat16, ... ) >>> # Download pipeline, but use a different scheduler >>> from diffusers import FlaxDPMSolverMultistepScheduler
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
>>> model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5" >>> dpmpp, dpmpp_state = FlaxDPMSolverMultistepScheduler.from_pretrained( ... model_id, ... subfolder="scheduler", ... ) >>> dpm_pipe, dpm_params = FlaxStableDiffusionPipeline.from_pretrained( ... model_id, variant="bf16", dtype=jnp.bfloat16, scheduler=dpmpp ... ) >>> dpm_params["scheduler"] = dpmpp_state ``` """ cache_dir = kwargs.pop("cache_dir", None) proxies = kwargs.pop("proxies", None) local_files_only = kwargs.pop("local_files_only", False) token = kwargs.pop("token", None) revision = kwargs.pop("revision", None) from_pt = kwargs.pop("from_pt", False) use_memory_efficient_attention = kwargs.pop("use_memory_efficient_attention", False) split_head_dim = kwargs.pop("split_head_dim", False) dtype = kwargs.pop("dtype", None)
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
# 1. Download the checkpoints and configs # use snapshot download here to get it working from from_pretrained if not os.path.isdir(pretrained_model_name_or_path): config_dict = cls.load_config( pretrained_model_name_or_path, cache_dir=cache_dir, proxies=proxies, local_files_only=local_files_only, token=token, revision=revision, ) # make sure we only download sub-folders and `diffusers` filenames folder_names = [k for k in config_dict.keys() if not k.startswith("_")] allow_patterns = [os.path.join(k, "*") for k in folder_names] allow_patterns += [FLAX_WEIGHTS_NAME, SCHEDULER_CONFIG_NAME, CONFIG_NAME, cls.config_name] ignore_patterns = ["*.bin", "*.safetensors"] if not from_pt else [] ignore_patterns += ["*.onnx", "*.onnx_data", "*.xml", "*.pb"]
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
if cls != FlaxDiffusionPipeline: requested_pipeline_class = cls.__name__ else: requested_pipeline_class = config_dict.get("_class_name", cls.__name__) requested_pipeline_class = ( requested_pipeline_class if requested_pipeline_class.startswith("Flax") else "Flax" + requested_pipeline_class ) user_agent = {"pipeline_class": requested_pipeline_class} user_agent = http_user_agent(user_agent)
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
# download all allow_patterns cached_folder = snapshot_download( pretrained_model_name_or_path, cache_dir=cache_dir, proxies=proxies, local_files_only=local_files_only, token=token, revision=revision, allow_patterns=allow_patterns, ignore_patterns=ignore_patterns, user_agent=user_agent, ) else: cached_folder = pretrained_model_name_or_path config_dict = cls.load_config(cached_folder)
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
# 2. Load the pipeline class, if using custom module then load it from the hub # if we load from explicit class, let's use it if cls != FlaxDiffusionPipeline: pipeline_class = cls else: diffusers_module = importlib.import_module(cls.__module__.split(".")[0]) class_name = ( config_dict["_class_name"] if config_dict["_class_name"].startswith("Flax") else "Flax" + config_dict["_class_name"] ) pipeline_class = getattr(diffusers_module, class_name) # some modules can be passed directly to the init # in this case they are already instantiated in `kwargs` # extract them here expected_modules, optional_kwargs = cls._get_signature_keys(pipeline_class) passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs} passed_pipe_kwargs = {k: kwargs.pop(k) for k in optional_kwargs if k in kwargs}
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
init_dict, unused_kwargs, _ = pipeline_class.extract_init_dict(config_dict, **kwargs) # define init kwargs init_kwargs = {k: init_dict.pop(k) for k in optional_kwargs if k in init_dict} init_kwargs = {**init_kwargs, **passed_pipe_kwargs} # remove `null` components def load_module(name, value): if value[0] is None: return False if name in passed_class_obj and passed_class_obj[name] is None: return False return True init_dict = {k: v for k, v in init_dict.items() if load_module(k, v)} # Throw nice warnings / errors for fast accelerate loading if len(unused_kwargs) > 0: logger.warning( f"Keyword arguments {unused_kwargs} are not expected by {pipeline_class.__name__} and will be ignored." ) # inference_params params = {} # import it here to avoid circular import from diffusers import pipelines
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
# 3. Load each module in the pipeline for name, (library_name, class_name) in init_dict.items(): if class_name is None: # edge case for when the pipeline was saved with safety_checker=None init_kwargs[name] = None continue is_pipeline_module = hasattr(pipelines, library_name) loaded_sub_model = None sub_model_should_be_defined = True # if the model is in a pipeline module, then we load it from the pipeline if name in passed_class_obj: # 1. check that passed_class_obj has correct parent class if not is_pipeline_module: library = importlib.import_module(library_name) class_obj = getattr(library, class_name) importable_classes = LOADABLE_CLASSES[library_name] class_candidates = {c: getattr(library, c, None) for c in importable_classes.keys()}
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
expected_class_obj = None for class_name, class_candidate in class_candidates.items(): if class_candidate is not None and issubclass(class_obj, class_candidate): expected_class_obj = class_candidate
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
if not issubclass(passed_class_obj[name].__class__, expected_class_obj): raise ValueError( f"{passed_class_obj[name]} is of type: {type(passed_class_obj[name])}, but should be" f" {expected_class_obj}" ) elif passed_class_obj[name] is None: logger.warning( f"You have passed `None` for {name} to disable its functionality in {pipeline_class}. Note" f" that this might lead to problems when using {pipeline_class} and is not recommended." ) sub_model_should_be_defined = False else: logger.warning( f"You have passed a non-standard module {passed_class_obj[name]}. We cannot verify whether it" " has the correct type" )
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
# set passed class object loaded_sub_model = passed_class_obj[name] elif is_pipeline_module: pipeline_module = getattr(pipelines, library_name) class_obj = import_flax_or_no_model(pipeline_module, class_name) importable_classes = ALL_IMPORTABLE_CLASSES class_candidates = {c: class_obj for c in importable_classes.keys()} else: # else we just import it from the library. library = importlib.import_module(library_name) class_obj = import_flax_or_no_model(library, class_name) importable_classes = LOADABLE_CLASSES[library_name] class_candidates = {c: getattr(library, c, None) for c in importable_classes.keys()}
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
if loaded_sub_model is None and sub_model_should_be_defined: load_method_name = None for class_name, class_candidate in class_candidates.items(): if class_candidate is not None and issubclass(class_obj, class_candidate): load_method_name = importable_classes[class_name][1] load_method = getattr(class_obj, load_method_name) # check if the module is in a subdirectory if os.path.isdir(os.path.join(cached_folder, name)): loadable_folder = os.path.join(cached_folder, name) else: loaded_sub_model = cached_folder
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
if issubclass(class_obj, FlaxModelMixin): loaded_sub_model, loaded_params = load_method( loadable_folder, from_pt=from_pt, use_memory_efficient_attention=use_memory_efficient_attention, split_head_dim=split_head_dim, dtype=dtype, ) params[name] = loaded_params elif is_transformers_available() and issubclass(class_obj, FlaxPreTrainedModel): if from_pt: # TODO(Suraj): Fix this in Transformers. We should be able to use `_do_init=False` here loaded_sub_model = load_method(loadable_folder, from_pt=from_pt) loaded_params = loaded_sub_model.params del loaded_sub_model._params else:
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
loaded_sub_model, loaded_params = load_method(loadable_folder, _do_init=False) params[name] = loaded_params elif issubclass(class_obj, FlaxSchedulerMixin): loaded_sub_model, scheduler_state = load_method(loadable_folder) params[name] = scheduler_state else: loaded_sub_model = load_method(loadable_folder)
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
init_kwargs[name] = loaded_sub_model # UNet(...), # DiffusionSchedule(...) # 4. Potentially add passed objects if expected missing_modules = set(expected_modules) - set(init_kwargs.keys()) passed_modules = list(passed_class_obj.keys()) if len(missing_modules) > 0 and missing_modules <= set(passed_modules): for module in missing_modules: init_kwargs[module] = passed_class_obj.get(module, None) elif len(missing_modules) > 0: passed_modules = set(list(init_kwargs.keys()) + list(passed_class_obj.keys())) - optional_kwargs raise ValueError( f"Pipeline {pipeline_class} expected {expected_modules}, but only {passed_modules} were passed." ) model = pipeline_class(**init_kwargs, dtype=dtype) return model, params
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
@classmethod def _get_signature_keys(cls, obj): parameters = inspect.signature(obj.__init__).parameters required_parameters = {k: v for k, v in parameters.items() if v.default == inspect._empty} optional_parameters = set({k for k, v in parameters.items() if v.default != inspect._empty}) expected_modules = set(required_parameters.keys()) - {"self"} return expected_modules, optional_parameters @property def components(self) -> Dict[str, Any]: r""" The `self.components` property can be useful to run different pipelines with the same weights and configurations to not have to re-allocate memory. Examples: ```py >>> from diffusers import ( ... FlaxStableDiffusionPipeline, ... FlaxStableDiffusionImg2ImgPipeline, ... )
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
>>> text2img = FlaxStableDiffusionPipeline.from_pretrained( ... "stable-diffusion-v1-5/stable-diffusion-v1-5", variant="bf16", dtype=jnp.bfloat16 ... ) >>> img2img = FlaxStableDiffusionImg2ImgPipeline(**text2img.components) ``` Returns: A dictionary containing all the modules needed to initialize the pipeline. """ expected_modules, optional_parameters = self._get_signature_keys(self) components = { k: getattr(self, k) for k in self.config.keys() if not k.startswith("_") and k not in optional_parameters } if set(components.keys()) != expected_modules: raise ValueError( f"{self} has been incorrectly initialized or {self.__class__} is incorrectly implemented. Expected" f" {expected_modules} to be defined, but {components} are defined." ) return components
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
@staticmethod def numpy_to_pil(images): """ Convert a NumPy image or a batch of images to a PIL image. """ if images.ndim == 3: images = images[None, ...] images = (images * 255).round().astype("uint8") if images.shape[-1] == 1: # special case for grayscale (single channel) images pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images] else: pil_images = [Image.fromarray(image) for image in images] return pil_images # TODO: make it compatible with jax.lax def progress_bar(self, iterable): if not hasattr(self, "_progress_bar_config"): self._progress_bar_config = {} elif not isinstance(self._progress_bar_config, dict): raise ValueError( f"`self._progress_bar_config` should be of type `dict`, but is {type(self._progress_bar_config)}." )
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
return tqdm(iterable, **self._progress_bar_config) def set_progress_bar_config(self, **kwargs): self._progress_bar_config = kwargs
31
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_flax_utils.py
class AutoPipelineForText2Image(ConfigMixin): r""" [`AutoPipelineForText2Image`] is a generic pipeline class that instantiates a text-to-image pipeline class. The specific underlying pipeline class is automatically selected from either the [`~AutoPipelineForText2Image.from_pretrained`] or [`~AutoPipelineForText2Image.from_pipe`] methods. This class cannot be instantiated using `__init__()` (throws an error). Class attributes: - **config_name** (`str`) -- The configuration filename that stores the class and module names of all the diffusion pipeline's components. """ config_name = "model_index.json" def __init__(self, *args, **kwargs): raise EnvironmentError( f"{self.__class__.__name__} is designed to be instantiated " f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or " f"`{self.__class__.__name__}.from_pipe(pipeline)` methods." )
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
@classmethod @validate_hf_hub_args def from_pretrained(cls, pretrained_model_or_path, **kwargs): r""" Instantiates a text-to-image Pytorch diffusion pipeline from pretrained pipeline weight. The from_pretrained() method takes care of returning the correct pipeline class instance by: 1. Detect the pipeline class of the pretrained_model_or_path based on the _class_name property of its config object 2. Find the text-to-image pipeline linked to the pipeline class using pattern matching on pipeline class name. If a `controlnet` argument is passed, it will instantiate a [`StableDiffusionControlNetPipeline`] object. The pipeline is set in evaluation mode (`model.eval()`) by default. If you get the error message below, you need to finetune the weights for your downstream task:
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
``` Some weights of UNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match: - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference. ``` Parameters: pretrained_model_or_path (`str` or `os.PathLike`, *optional*): Can be either:
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
- A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline hosted on the Hub. - A path to a *directory* (for example `./my_pipeline_directory/`) containing pipeline weights saved using [`~DiffusionPipeline.save_pretrained`]. torch_dtype (`str` or `torch.dtype`, *optional*): Override the default `torch.dtype` and load the model with another dtype. If "auto" is passed, the dtype is automatically derived from the model's weights. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. cache_dir (`Union[str, os.PathLike]`, *optional*):
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache is not used.
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_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. output_loading_info(`bool`, *optional*, defaults to `False`): Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages. local_files_only (`bool`, *optional*, defaults to `False`): Whether to only load local model weights and configuration files or not. If set to `True`, the model won't be downloaded from the Hub. token (`str` or *bool*, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from `diffusers-cli login` (stored in `~/.huggingface`) is used. revision (`str`, *optional*, defaults to `"main"`):
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier allowed by Git. custom_revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id similar to `revision` when loading a custom pipeline from the Hub. It can be a 🤗 Diffusers version when loading a custom pipeline from GitHub, otherwise it defaults to `"main"` when loading from the Hub. mirror (`str`, *optional*): Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not guarantee the timeliness or safety of the source, and you should refer to the mirror site for more information. device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
A map that specifies where each submodule should go. It doesn’t need to be defined for each parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the same device.
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For more information about each option see [designing a device map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map). max_memory (`Dict`, *optional*): A dictionary device identifier for the maximum memory. Will default to the maximum memory available for each GPU and the available CPU RAM if unset. offload_folder (`str` or `os.PathLike`, *optional*): The path to offload weights if device_map contains the value `"disk"`. offload_state_dict (`bool`, *optional*): If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
when there is some disk offload. low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`): Speed up model loading only loading the pretrained weights and not initializing the weights. This also tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model. Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this argument to `True` will raise an error. use_safetensors (`bool`, *optional*, defaults to `None`): If set to `None`, the safetensors weights are downloaded if they're available **and** if the safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors weights. If set to `False`, safetensors weights are not loaded. kwargs (remaining dictionary of keyword arguments, *optional*):
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline class). The overwritten components are passed directly to the pipelines `__init__` method. See example below for more information. variant (`str`, *optional*): Load weights from a specified variant filename such as `"fp16"` or `"ema"`. This is ignored when loading `from_flax`.
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
<Tip> To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with `huggingface-cli login`. </Tip> Examples: ```py >>> from diffusers import AutoPipelineForText2Image >>> pipeline = AutoPipelineForText2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5") >>> image = pipeline(prompt).images[0] ``` """ cache_dir = kwargs.pop("cache_dir", None) force_download = kwargs.pop("force_download", False) proxies = kwargs.pop("proxies", None) token = kwargs.pop("token", None) local_files_only = kwargs.pop("local_files_only", False) revision = kwargs.pop("revision", None)
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
load_config_kwargs = { "cache_dir": cache_dir, "force_download": force_download, "proxies": proxies, "token": token, "local_files_only": local_files_only, "revision": revision, } config = cls.load_config(pretrained_model_or_path, **load_config_kwargs) orig_class_name = config["_class_name"] if "ControlPipeline" in orig_class_name: to_replace = "ControlPipeline" else: to_replace = "Pipeline"
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
if "controlnet" in kwargs: if isinstance(kwargs["controlnet"], ControlNetUnionModel): orig_class_name = config["_class_name"].replace(to_replace, "ControlNetUnionPipeline") else: orig_class_name = config["_class_name"].replace(to_replace, "ControlNetPipeline") if "enable_pag" in kwargs: enable_pag = kwargs.pop("enable_pag") if enable_pag: orig_class_name = orig_class_name.replace(to_replace, "PAGPipeline") text_2_image_cls = _get_task_class(AUTO_TEXT2IMAGE_PIPELINES_MAPPING, orig_class_name) kwargs = {**load_config_kwargs, **kwargs} return text_2_image_cls.from_pretrained(pretrained_model_or_path, **kwargs) @classmethod def from_pipe(cls, pipeline, **kwargs): r""" Instantiates a text-to-image Pytorch diffusion pipeline from another instantiated diffusion pipeline class.
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
The from_pipe() method takes care of returning the correct pipeline class instance by finding the text-to-image pipeline linked to the pipeline class using pattern matching on pipeline class name. All the modules the pipeline contains will be used to initialize the new pipeline without reallocating additional memory. The pipeline is set in evaluation mode (`model.eval()`) by default. Parameters: pipeline (`DiffusionPipeline`): an instantiated `DiffusionPipeline` object ```py >>> from diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image >>> pipe_i2i = AutoPipelineForImage2Image.from_pretrained( ... "stable-diffusion-v1-5/stable-diffusion-v1-5", requires_safety_checker=False ... ) >>> pipe_t2i = AutoPipelineForText2Image.from_pipe(pipe_i2i) >>> image = pipe_t2i(prompt).images[0] ``` """
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py
original_config = dict(pipeline.config) original_cls_name = pipeline.__class__.__name__ # derive the pipeline class to instantiate text_2_image_cls = _get_task_class(AUTO_TEXT2IMAGE_PIPELINES_MAPPING, original_cls_name) if "controlnet" in kwargs: if kwargs["controlnet"] is not None: to_replace = "PAGPipeline" if "PAG" in text_2_image_cls.__name__ else "Pipeline" text_2_image_cls = _get_task_class( AUTO_TEXT2IMAGE_PIPELINES_MAPPING, text_2_image_cls.__name__.replace("ControlNet", "").replace(to_replace, "ControlNet" + to_replace), ) else: text_2_image_cls = _get_task_class( AUTO_TEXT2IMAGE_PIPELINES_MAPPING, text_2_image_cls.__name__.replace("ControlNet", ""), )
32
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py