text
stringlengths
1
1.02k
class_index
int64
0
1.38k
source
stringclasses
431 values
Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method. vae_scale_factor (`int...
6
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py
do_convert_grayscale (`bool`, *optional*, defaults to be `False`): Whether to convert the images to grayscale format. """
6
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py
@register_to_config def __init__( self, do_resize: bool = True, vae_scale_factor: int = 8, resample: str = "lanczos", do_normalize: bool = True, do_binarize: bool = False, do_convert_grayscale: bool = False, ): super().__init__( do_resi...
6
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py
Returns: `Tuple[int, int]`: The closest binned height and width. """ ar = float(height / width) closest_ratio = min(ratios.keys(), key=lambda ratio: abs(float(ratio) - ar)) default_hw = ratios[closest_ratio] return int(default_hw[0]), int(default_hw[1]) @staticme...
6
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py
Returns: `torch.Tensor`: A tensor containing the resized and cropped images. """ orig_height, orig_width = samples.shape[2], samples.shape[3] # Check if resizing is needed if orig_height != new_height or orig_width != new_width: ratio = max(new_height / orig_heig...
6
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/image_processor.py
class VideoProcessor(VaeImageProcessor): r"""Simple video processor.""" def preprocess_video(self, video, height: Optional[int] = None, width: Optional[int] = None) -> torch.Tensor: r""" Preprocesses input video(s).
7
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/video_processor.py
Args: video (`List[PIL.Image]`, `List[List[PIL.Image]]`, `torch.Tensor`, `np.array`, `List[torch.Tensor]`, `List[np.array]`): The input video. It can be one of the following: * List of the PIL images. * List of list of PIL images. * 4D Torch te...
7
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/video_processor.py
* 5D Torch tensors: expected shape for each array `(batch_size, num_frames, num_channels, height, width)`. height (`int`, *optional*, defaults to `None`): The height in preprocessed frames of the video. If `None`, will use the `get_default_height_width()` to ...
7
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/video_processor.py
if isinstance(video, list) and isinstance(video[0], torch.Tensor) and video[0].ndim == 5: warnings.warn( "Passing `video` as a list of 5d torch.Tensor is deprecated." "Please concatenate the list along the batch dimension and pass it as a single 5d torch.Tensor", ...
7
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/video_processor.py
# ensure the input is a list of videos: # - if it is a batch of videos (5d torch.Tensor or np.ndarray), it is converted to a list of videos (a list of 4d torch.Tensor or np.ndarray) # - if it is is a single video, it is convereted to a list of one video. if isinstance(video, (np.ndarray, torch.T...
7
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/video_processor.py
return video def postprocess_video( self, video: torch.Tensor, output_type: str = "np" ) -> Union[np.ndarray, torch.Tensor, List[PIL.Image.Image]]: r""" Converts a video tensor to a list of frames for export. Args: video (`torch.Tensor`): The video as a tensor. ...
7
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/video_processor.py
return outputs
7
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/video_processor.py
class SchedulerType(Enum): LINEAR = "linear" COSINE = "cosine" COSINE_WITH_RESTARTS = "cosine_with_restarts" POLYNOMIAL = "polynomial" CONSTANT = "constant" CONSTANT_WITH_WARMUP = "constant_with_warmup" PIECEWISE_CONSTANT = "piecewise_constant"
8
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/optimization.py
class EMAModel: """ Exponential Moving Average of models weights """
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
def __init__( self, parameters: Iterable[torch.nn.Parameter], decay: float = 0.9999, min_decay: float = 0.0, update_after_step: int = 0, use_ema_warmup: bool = False, inv_gamma: Union[float, int] = 1.0, power: Union[float, int] = 2 / 3, foreach: bo...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
Inverse multiplicative factor of EMA warmup. Default: 1. Only used if `use_ema_warmup` is True. power (float): Exponential factor of EMA warmup. Default: 2/3. Only used if `use_ema_warmup` is True. foreach (bool): Use torch._foreach functions for updating shadow parameters. Should be faster. ...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
@crowsonkb's notes on EMA Warmup: If gamma=1 and power=1, implements a simple average. gamma=1, power=2/3 are good values for models you plan to train for a million or more steps (reaches decay factor 0.999 at 31.6K steps, 0.9999 at 1M steps), gamma=1, power=3/4 for models you plan t...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
# set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility use_ema_warmup = True if kwargs.get("max_value", None) is not None: deprecation_message = "The `max_value` argument is deprecated. Please use `decay` instead." deprecate("max_value", "1.0...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
if kwargs.get("device", None) is not None: deprecation_message = "The `device` argument is deprecated. Please use `to` instead." deprecate("device", "1.0.0", deprecation_message, standard_warn=False) self.to(device=kwargs["device"]) self.temp_stored_params = None se...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
ema_model = cls(model.parameters(), model_cls=model_cls, model_config=model.config, foreach=foreach) ema_model.load_state_dict(ema_kwargs) return ema_model def save_pretrained(self, path): if self.model_cls is None: raise ValueError("`save_pretrained` can only be used if `model...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
if step <= 0: return 0.0 if self.use_ema_warmup: cur_decay_value = 1 - (1 + step / self.inv_gamma) ** -self.power else: cur_decay_value = (1 + step) / (10 + step) cur_decay_value = min(cur_decay_value, self.decay) # make sure decay is not smaller tha...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
@torch.no_grad() def step(self, parameters: Iterable[torch.nn.Parameter]): if isinstance(parameters, torch.nn.Module): deprecation_message = ( "Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. " "Please pass the parameters of the modul...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
if self.foreach: if is_transformers_available() and transformers.integrations.deepspeed.is_deepspeed_zero3_enabled(): context_manager = deepspeed.zero.GatheredParameters(parameters, modifier_rank=None) with context_manager: params_grad = [param for param in param...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
torch._foreach_sub_( s_params_grad, torch._foreach_sub(s_params_grad, params_grad), alpha=one_minus_decay ) else: for s_param, param in zip(self.shadow_params, parameters): if is_transformers_available() and transformers.integrations.deepspeed.is_...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
Args: parameters: Iterable of `torch.nn.Parameter`; the parameters to be updated with the stored moving averages. If `None`, the parameters with which this `ExponentialMovingAverage` was initialized will be used. """ parameters = list(parameters) if se...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
def to(self, device=None, dtype=None, non_blocking=False) -> None: r""" Move internal buffers of the ExponentialMovingAverage to `device`. Args: device: like `device` argument to `torch.Tensor.to` """ # .to() on the tensors handles None correctly self.shadow_...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
def state_dict(self) -> dict: r""" Returns the state of the ExponentialMovingAverage as a dict. This method is used by accelerate during checkpointing to save the ema state dict. """ # Following PyTorch conventions, references to tensors are returned: # "returns a referen...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
Args: parameters: Iterable of `torch.nn.Parameter`. The parameters to be temporarily stored. """ self.temp_stored_params = [param.detach().cpu().clone() for param in parameters] def restore(self, parameters: Iterable[torch.nn.Parameter]) -> None: r""" Restore the paramet...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
if self.temp_stored_params is None: raise RuntimeError("This ExponentialMovingAverage has no `store()`ed weights " "to `restore()`") if self.foreach: torch._foreach_copy_( [param.data for param in parameters], [c_param.data for c_param in self.temp_stored_params] ...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
self.decay = state_dict.get("decay", self.decay) if self.decay < 0.0 or self.decay > 1.0: raise ValueError("Decay must be between 0 and 1") self.min_decay = state_dict.get("min_decay", self.min_decay) if not isinstance(self.min_decay, float): raise ValueError("Invalid mi...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
self.inv_gamma = state_dict.get("inv_gamma", self.inv_gamma) if not isinstance(self.inv_gamma, (float, int)): raise ValueError("Invalid inv_gamma") self.power = state_dict.get("power", self.power) if not isinstance(self.power, (float, int)): raise ValueError("Invalid pow...
9
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/training_utils.py
class PipelineCallback(ConfigMixin): """ Base class for all the official callbacks used in a pipeline. This class provides a structure for implementing custom callbacks and ensures that all callbacks have a consistent interface. Please implement the following: `tensor_inputs`: This should retur...
10
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/callbacks.py
if (cutoff_step_ratio is None and cutoff_step_index is None) or ( cutoff_step_ratio is not None and cutoff_step_index is not None ): raise ValueError("Either cutoff_step_ratio or cutoff_step_index should be provided, not both or none.") if cutoff_step_ratio is not None and ( ...
10
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/callbacks.py
def __call__(self, pipeline, step_index, timestep, callback_kwargs) -> Dict[str, Any]: return self.callback_fn(pipeline, step_index, timestep, callback_kwargs)
10
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/callbacks.py
class MultiPipelineCallbacks: """ This class is designed to handle multiple pipeline callbacks. It accepts a list of PipelineCallback objects and provides a unified interface for calling all of them. """ def __init__(self, callbacks: List[PipelineCallback]): self.callbacks = callbacks ...
11
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/callbacks.py
class SDCFGCutoffCallback(PipelineCallback): """ Callback function for Stable Diffusion Pipelines. After certain number of steps (set by `cutoff_step_ratio` or `cutoff_step_index`), this callback will disable the CFG. Note: This callback mutates the pipeline by changing the `_guidance_scale` attribute ...
12
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/callbacks.py
if step_index == cutoff_step: prompt_embeds = callback_kwargs[self.tensor_inputs[0]] prompt_embeds = prompt_embeds[-1:] # "-1" denotes the embeddings for conditional text tokens. pipeline._guidance_scale = 0.0 callback_kwargs[self.tensor_inputs[0]] = prompt_embeds ...
12
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/callbacks.py
class SDXLCFGCutoffCallback(PipelineCallback): """ Callback function for the base Stable Diffusion XL Pipelines. After certain number of steps (set by `cutoff_step_ratio` or `cutoff_step_index`), this callback will disable the CFG. Note: This callback mutates the pipeline by changing the `_guidance_sca...
13
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/callbacks.py
if step_index == cutoff_step: prompt_embeds = callback_kwargs[self.tensor_inputs[0]] prompt_embeds = prompt_embeds[-1:] # "-1" denotes the embeddings for conditional text tokens. add_text_embeds = callback_kwargs[self.tensor_inputs[1]] add_text_embeds = add_text_embeds[...
13
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/callbacks.py
class SDXLControlnetCFGCutoffCallback(PipelineCallback): """ Callback function for the Controlnet Stable Diffusion XL Pipelines. After certain number of steps (set by `cutoff_step_ratio` or `cutoff_step_index`), this callback will disable the CFG. Note: This callback mutates the pipeline by changing th...
14
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/callbacks.py
if step_index == cutoff_step: prompt_embeds = callback_kwargs[self.tensor_inputs[0]] prompt_embeds = prompt_embeds[-1:] # "-1" denotes the embeddings for conditional text tokens. add_text_embeds = callback_kwargs[self.tensor_inputs[1]] add_text_embeds = add_text_embeds[...
14
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/callbacks.py
return callback_kwargs
14
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/callbacks.py
class IPAdapterScaleCutoffCallback(PipelineCallback): """ Callback function for any pipeline that inherits `IPAdapterMixin`. After certain number of steps (set by `cutoff_step_ratio` or `cutoff_step_index`), this callback will set the IP Adapter scale to `0.0`. Note: This callback mutates the IP Adapte...
15
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/callbacks.py
class ValueGuidedRLPipeline(DiffusionPipeline): r""" Pipeline for value-guided sampling from a diffusion model trained to predict sequences of states. This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods implemented for all pipelines (downloading, s...
16
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/experimental/rl/value_guided_sampling.py
def __init__( self, value_function: UNet1DModel, unet: UNet1DModel, scheduler: DDPMScheduler, env, ): super().__init__() self.register_modules(value_function=value_function, unet=unet, scheduler=scheduler, env=env) self.data = env.get_dataset() ...
16
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/experimental/rl/value_guided_sampling.py
def to_torch(self, x_in): if isinstance(x_in, dict): return {k: self.to_torch(v) for k, v in x_in.items()} elif torch.is_tensor(x_in): return x_in.to(self.unet.device) return torch.tensor(x_in, device=self.unet.device) def reset_x0(self, x_in, cond, act_dim): ...
16
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/experimental/rl/value_guided_sampling.py
# permute to match dimension for pre-trained models y = self.value_function(x.permute(0, 2, 1), timesteps).sample grad = torch.autograd.grad([y.sum()], [x])[0] posterior_variance = self.scheduler._get_variance(i) model_std = torch.exp(0.5 ...
16
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/experimental/rl/value_guided_sampling.py
def __call__(self, obs, batch_size=64, planning_horizon=32, n_guide_steps=2, scale=0.1): # normalize the observations and create batch dimension obs = self.normalize(obs, "observations") obs = obs[None].repeat(batch_size, axis=0) conditions = {0: self.to_torch(obs)} shape = (ba...
16
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/experimental/rl/value_guided_sampling.py
# sort output trajectories by value sorted_idx = y.argsort(0, descending=True).squeeze() sorted_values = x[sorted_idx] actions = sorted_values[:, :, : self.action_dim] actions = actions.detach().cpu().numpy() denorm_actions = self.de_normalize(actions, key="actions") # s...
16
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/experimental/rl/value_guided_sampling.py
class QuantizationMethod(str, Enum): BITS_AND_BYTES = "bitsandbytes" GGUF = "gguf" TORCHAO = "torchao"
17
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
class QuantizationConfigMixin: """ Mixin class for quantization config """ quant_method: QuantizationMethod _exclude_attributes_at_init = [] @classmethod def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs): """ Instantiates a [`QuantizationConfigMixin`] fr...
18
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
to_remove = [] for key, value in kwargs.items(): if hasattr(config, key): setattr(config, key, value) to_remove.append(key) for key in to_remove: kwargs.pop(key, None) if return_unused_kwargs: return config, kwargs else...
18
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
Args: json_file_path (`str` or `os.PathLike`): Path to the JSON file in which this configuration instance's parameters will be saved. use_diff (`bool`, *optional*, defaults to `True`): If set to `True`, only the difference between the config instance and the defau...
18
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
def __iter__(self): """allows `dict(obj)` for situations where obj may be a dict or QuantizationConfigMixin""" for attr, value in copy.deepcopy(self.__dict__).items(): yield attr, value def __repr__(self): return f"{self.__class__.__name__} {self.to_json_string()}" def to_j...
18
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
def update(self, **kwargs): """ Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes, returning all the unused kwargs. Args: kwargs (`Dict[str, Any]`): Dictionary of attributes to tentatively update this cl...
18
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
class BitsAndBytesConfig(QuantizationConfigMixin): """ This is a wrapper class about all possible attributes and features that you can play with a model that has been loaded using `bitsandbytes`. This replaces `load_in_8bit` or `load_in_4bit`therefore both options are mutually exclusive. Currently...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
Args: load_in_8bit (`bool`, *optional*, defaults to `False`): This flag is used to enable 8-bit quantization with LLM.int8(). load_in_4bit (`bool`, *optional*, defaults to `False`): This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers ...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
These outliers are often in the interval [-60, -6] or [6, 60]. Int8 quantization works well for values of magnitude ~5, but beyond that, there is a significant performance penalty. A good default threshold is 6, but a lower threshold might be needed for more unstable models (small models, fine-t...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
your model in different parts and run some parts in int8 on GPU and some parts in fp32 on CPU, you can use this flag. This is useful for offloading large models such as `google/flan-t5-xxl`. Note that the int8 operations will not be run on CPU. llm_int8_has_fp16_weight (`bool`, *optional...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
which are specified by `fp4` or `nf4`. bnb_4bit_use_double_quant (`bool`, *optional*, defaults to `False`): This flag is used for nested quantization where the quantization constants from the first quantization are quantized again. bnb_4bit_quant_storage (`torch.dtype` or str, *o...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
_exclude_attributes_at_init = ["_load_in_4bit", "_load_in_8bit", "quant_method"] def __init__( self, load_in_8bit=False, load_in_4bit=False, llm_int8_threshold=6.0, llm_int8_skip_modules=None, llm_int8_enable_fp32_cpu_offload=False, llm_int8_has_fp16_weight=F...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
self._load_in_8bit = load_in_8bit self._load_in_4bit = load_in_4bit self.llm_int8_threshold = llm_int8_threshold self.llm_int8_skip_modules = llm_int8_skip_modules self.llm_int8_enable_fp32_cpu_offload = llm_int8_enable_fp32_cpu_offload self.llm_int8_has_fp16_weight = llm_int8_ha...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
if bnb_4bit_quant_storage is None: self.bnb_4bit_quant_storage = torch.uint8 elif isinstance(bnb_4bit_quant_storage, str): if bnb_4bit_quant_storage not in ["float16", "float32", "int8", "uint8", "float64", "bfloat16"]: raise ValueError( "`bnb_4bit_qua...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
@property def load_in_4bit(self): return self._load_in_4bit @load_in_4bit.setter def load_in_4bit(self, value: bool): if not isinstance(value, bool): raise TypeError("load_in_4bit must be a boolean") if self.load_in_8bit and value: raise ValueError("load_in_...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
def post_init(self): r""" Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. """ if not isinstance(self.load_in_4bit, bool): raise TypeError("load_in_4bit must be a boolean") if not isinstance(self.load_in_8bi...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
if self.bnb_4bit_compute_dtype is not None and not isinstance(self.bnb_4bit_compute_dtype, torch.dtype): raise TypeError("bnb_4bit_compute_dtype must be torch.dtype") if not isinstance(self.bnb_4bit_quant_type, str): raise TypeError("bnb_4bit_quant_type must be a string") if no...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
def quantization_method(self): r""" This method returns the quantization method used for the model. If the model is not quantizable, it returns `None`. """ if self.load_in_8bit: return "llm_int8" elif self.load_in_4bit and self.bnb_4bit_quant_type == "fp4": ...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
def to_dict(self) -> Dict[str, Any]: """ Serializes this instance to a Python dictionary. Returns: `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance. """ output = copy.deepcopy(self.__dict__) output["bnb_4bit_compute_dtype"] =...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
Returns: `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance, """ config_dict = self.to_dict() # get the default config dict default_config_dict = BitsAndBytesConfig().to_dict() serializable_config_dict = {} # only se...
19
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
class GGUFQuantizationConfig(QuantizationConfigMixin): """This is a config class for GGUF Quantization techniques. Args: compute_dtype: (`torch.dtype`, defaults to `torch.float32`): This sets the computational type which might be different than the input type. For example, inputs might be ...
20
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
class TorchAoConfig(QuantizationConfigMixin): """This is a config class for torchao quantization/sparsity techniques. Args: quant_type (`str`): The type of quantization we want to use, currently supporting: - **Integer quantization:** - Full function name...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
- **Floating point X-bit quantization:** - Full function names: `fpx_weight_only` - Shorthands: `fpX_eAwB`, where `X` is the number of bits (between `1` to `7`), `A` is the number of exponent bits and `B` is the number of mantissa bits. The constraint of `X ...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
- **Unsigned Integer quantization:** - Full function names: `uintx_weight_only` - Shorthands: `uint1wo`, `uint2wo`, `uint3wo`, `uint4wo`, `uint5wo`, `uint6wo`, `uint7wo` modules_to_not_convert (`List[str]`, *optional*, default to `None`): The list of modules t...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
quantization_config = TorchAoConfig("int8wo") transformer = FluxTransformer2DModel.from_pretrained( "black-forest-labs/Flux.1-Dev", subfolder="transformer", quantization_config=quantization_config, torch_dtype=torch.bfloat16, ) ``` """ def...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
TORCHAO_QUANT_TYPE_METHODS = self._get_torchao_quant_type_to_method() if self.quant_type not in TORCHAO_QUANT_TYPE_METHODS.keys(): raise ValueError( f"Requested quantization type: {self.quant_type} is not supported yet or is incorrect. If you think the " f"provided qu...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
if len(unsupported_kwargs) > 0: raise ValueError( f'The quantization method "{quant_type}" does not support the following keyword arguments: ' f"{unsupported_kwargs}. The following keywords arguments are supported: {all_kwargs}." ) @classmethod def _get_t...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
# TODO(aryan): Add a note on how to use PerAxis and PerGroup observers from torchao.quantization.observer import PerRow, PerTensor def generate_float8dq_types(dtype: torch.dtype): name = "e5m2" if dtype == torch.float8_e5m2 else "e4m3" types = {} ...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
for ebits in range(1, bits): mbits = bits - ebits - 1 types[f"fp{bits}_e{ebits}m{mbits}"] = partial(fpx_weight_only, ebits=ebits, mbits=mbits) non_sign_bits = bits - 1 default_ebits = (non_sign_bits + 1) // 2 default_mbits = non_si...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
INT8_QUANTIZATION_TYPES = { # int8 weight + bfloat16/float16 activation "int8wo": int8_weight_only, "int8_weight_only": int8_weight_only, # int8 weight + int8 activation "int8dq": int8_dynamic_activation_int8_weight, "int8_d...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
# TODO(aryan): handle torch 2.2/2.3 FLOATX_QUANTIZATION_TYPES = { # float8_e5m2 weight + bfloat16/float16 activation "float8wo": partial(float8_weight_only, weight_dtype=torch.float8_e5m2), "float8_weight_only": float8_weight_only, "float8wo_e5...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
# "float8dq_e5m2": partial( # float8_dynamic_activation_float8_weight, # activation_dtype=torch.float8_e5m2, # weight_dtype=torch.float8_e5m2, # ), # **generate_float8dq_types(torch.float8_e5m2), # ===== ===== ...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
# fpx weight + bfloat16/float16 activation **generate_fpx_quantization_types(3), **generate_fpx_quantization_types(4), **generate_fpx_quantization_types(5), **generate_fpx_quantization_types(6), **generate_fpx_quantization_types(7), ...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
UINTX_QUANTIZATION_DTYPES = { "uintx_weight_only": uintx_weight_only, "uint1wo": partial(uintx_weight_only, dtype=torch.uint1), "uint2wo": partial(uintx_weight_only, dtype=torch.uint2), "uint3wo": partial(uintx_weight_only, dtype=torch.uint3), ...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
if cls._is_cuda_capability_atleast_8_9(): QUANTIZATION_TYPES.update(FLOATX_QUANTIZATION_TYPES) return QUANTIZATION_TYPES else: raise ValueError( "TorchAoConfig requires torchao to be installed, please install with `pip install torchao`" ) ...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
``` TorchAoConfig { "modules_to_not_convert": null, "quant_method": "torchao", "quant_type": "uint_a16w4", "quant_type_kwargs": { "group_size": 32 } } ``` """ config_dict = self.to_dict() return f...
21
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/quantization_config.py
class DiffusersQuantizer(ABC): """ Abstract class of the HuggingFace quantizer. Supports for now quantizing HF diffusers models for inference and/or quantization. This class is used only for diffusers.models.modeling_utils.ModelMixin.from_pretrained and cannot be easily used outside the scope of that me...
22
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/base.py
requires_calibration = False required_packages = None def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs): self.quantization_config = quantization_config # -- Handle extra kwargs below -- self.modules_to_not_convert = kwargs.pop("modules_to_not_convert", []) ...
22
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/base.py
def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype": """ Some quantization methods require to explicitly set the dtype of the model to a target dtype. You need to override this method in case you want to make sure that behavior is preserved Args: torch_...
22
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/base.py
def adjust_target_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype": """ Override this method if you want to adjust the `target_dtype` variable used in `from_pretrained` to compute the device_map in case the device_map is a `str`. E.g. for bitsandbytes we force-set `target_dtype` to `torc...
22
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/base.py
def get_special_dtypes_update(self, model, torch_dtype: "torch.dtype") -> Dict[str, "torch.dtype"]: """ returns dtypes for modules that are not quantized - used for the computation of the device_map in case one passes a str as a device_map. The method will use the `modules_to_not_convert` that i...
22
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/base.py
def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]: """adjust max_memory argument for infer_auto_device_map() if extra memory is needed for quantization""" return max_memory def check_if_quantized_param( self, model: "ModelMixin", ...
22
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/base.py
def check_quantized_param_shape(self, *args, **kwargs): """ checks if the quantized param has expected shape. """ return True def validate_environment(self, *args, **kwargs): """ This method is used to potentially check for potential conflicts with arguments that are...
22
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/base.py
Args: model (`~diffusers.models.modeling_utils.ModelMixin`): The model to quantize kwargs (`dict`, *optional*): The keyword arguments that are passed along `_process_model_before_weight_loading`. """ model.is_quantized = True model.quantiza...
22
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/base.py
def dequantize(self, model): """ Potentially dequantize the model to retrive the original model, with some loss in accuracy / performance. Note not all quantization schemes support this. """ model = self._dequantize(model) # Delete quantizer and quantization config ...
22
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/base.py
class DiffusersAutoQuantizer: """ The auto diffusers quantizer class that takes care of automatically instantiating to the correct `DiffusersQuantizer` given the `QuantizationConfig`. """ @classmethod def from_dict(cls, quantization_config_dict: Dict): quant_method = quantization_confi...
23
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/auto.py
if quant_method not in AUTO_QUANTIZATION_CONFIG_MAPPING.keys(): raise ValueError( f"Unknown quantization type, got {quant_method} - supported types are:" f" {list(AUTO_QUANTIZER_MAPPING.keys())}" ) target_cls = AUTO_QUANTIZATION_CONFIG_MAPPING[quant_metho...
23
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/auto.py
# Again, we need a special care for bnb as we have a single quantization config # class for both 4-bit and 8-bit quantization if quant_method == QuantizationMethod.BITS_AND_BYTES: if quantization_config.load_in_8bit: quant_method += "_8bit" else: q...
23
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/auto.py
@classmethod def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): model_config = cls.load_config(pretrained_model_name_or_path, **kwargs) if getattr(model_config, "quantization_config", None) is None: raise ValueError( f"Did not found a `quantization_config`...
23
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/auto.py
@classmethod def merge_quantization_configs( cls, quantization_config: Union[dict, QuantizationConfigMixin], quantization_config_from_args: Optional[QuantizationConfigMixin], ): """ handles situations where both quantization_config from args and quantization_config from m...
23
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/auto.py
class GGUFQuantizer(DiffusersQuantizer): use_keep_in_fp32_modules = True def __init__(self, quantization_config, **kwargs): super().__init__(quantization_config, **kwargs) self.compute_dtype = quantization_config.compute_dtype self.pre_quantized = quantization_config.pre_quantized ...
24
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/quantizers/gguf/gguf_quantizer.py