text
stringlengths
1
1.02k
class_index
int64
0
1.38k
source
stringclasses
431 values
# this becomes applicable when the variant is not None. if variant is not None and (index_file is None or not os.path.exists(index_file)): index_file = _fetch_index_file_legacy(**index_file_kwargs) if index_file is not None and (dduf_entries or index_file.is_file()): is_sharded =...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
if is_sharded and from_flax: raise ValueError("Loading of sharded checkpoints is not supported when `from_flax=True`.") # load model model_file = None if from_flax: model_file = _get_model_file( pretrained_model_name_or_path, weights_name=...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
model = load_flax_checkpoint_in_pytorch_model(model, model_file) else: # in the case it is sharded, we have already the index if is_sharded: sharded_ckpt_cached_folder, sharded_metadata = _get_checkpoint_shard_files( pretrained_model_name_or_path, ...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
) logger.info("Merged sharded checkpoints as `hf_quantizer` is not None.") is_sharded = False
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
elif use_safetensors and not is_sharded: try: model_file = _get_model_file( pretrained_model_name_or_path, weights_name=_add_variant(SAFETENSORS_WEIGHTS_NAME, variant), cache_dir=cache_dir, ...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
except IOError as e: logger.error(f"An error occurred while trying to fetch {pretrained_model_name_or_path}: {e}") if not allow_pickle: raise logger.warning( "Defaulting to unsafe serialization. Pass `allow_pickl...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
if model_file is None and not is_sharded: model_file = _get_model_file( pretrained_model_name_or_path, weights_name=_add_variant(WEIGHTS_NAME, variant), cache_dir=cache_dir, force_download=force_download, ...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
if hf_quantizer is not None: hf_quantizer.preprocess_model( model=model, device_map=device_map, keep_in_fp32_modules=keep_in_fp32_modules )
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
# if device_map is None, load the state dict and move the params from meta device to the cpu if device_map is None and not is_sharded: # `torch.cuda.current_device()` is fine here when `hf_quantizer` is not None. # It would error out during the `validate_environme...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
# move the params from meta device to cpu missing_keys = set(model.state_dict().keys()) - set(state_dict.keys()) if hf_quantizer is not None: missing_keys = hf_quantizer.update_missing_keys(model, missing_keys, prefix="") if len(missing...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
unexpected_keys = load_model_dict_into_meta( model, state_dict, device=param_device, dtype=torch_dtype, model_name_or_path=pretrained_model_name_or_path, hf_quantizer=hf_quanti...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
else: # else let accelerate handle loading and dispatching. # Load weights and dispatch according to the device_map # by default the device_map is None and the weights are loaded on the CPU device_map = _determine_device_map( model, de...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
dtype=torch_dtype, strict=True, ) except AttributeError as e: # When using accelerate loading, we do not have the ability to load the state # dict and rename the weight names manually. Additionally, a...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
if "'Attention' object has no attribute" in str(e): logger.warning( f"Taking `{str(e)}` while using `accelerate.load_checkpoint_and_dispatch` to mean {pretrained_model_name_or_path}" " was saved with deprecated attention block w...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
model_file if not is_sharded else index_file, device_map, max_memory=max_memory, offload_folder=offload_folder, offload_state_dict=offload_state_dict, dtype=tor...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
loading_info = { "missing_keys": [], "unexpected_keys": [], "mismatched_keys": [], "error_msgs": [], } else: model = cls.from_config(config, **unused_kwargs) state_dict = load_sta...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
loading_info = { "missing_keys": missing_keys, "unexpected_keys": unexpected_keys, "mismatched_keys": mismatched_keys, "error_msgs": error_msgs, } if hf_quantizer is not None: hf_quantizer.postprocess_mo...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
if hf_quantizer is not None: # We also make sure to purge `_pre_quantization_dtype` when we serialize # the model config because `_pre_quantization_dtype` is `torch.dtype`, not JSON serializable. model.register_to_config(_name_or_path=pretrained_model_name_or_path, _pre_quantization_...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
# Adapted from `transformers`. @wraps(torch.nn.Module.cuda) def cuda(self, *args, **kwargs): # Checks if the model has been loaded in 4-bit or 8-bit with BNB if getattr(self, "quantization_method", None) == QuantizationMethod.BITS_AND_BYTES: if getattr(self, "is_loaded_in_8bit", Fals...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
# Adapted from `transformers`. @wraps(torch.nn.Module.to) def to(self, *args, **kwargs): dtype_present_in_args = "dtype" in kwargs if not dtype_present_in_args: for arg in args: if isinstance(arg, torch.dtype): dtype_present_in_args = True ...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
if getattr(self, "quantization_method", None) == QuantizationMethod.BITS_AND_BYTES: if getattr(self, "is_loaded_in_8bit", False): raise ValueError( "`.to` is not supported for `8-bit` bitsandbytes models. Please use the model as it is, since the" " mod...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
# Taken from `transformers`. def half(self, *args): # Checks if the model is quantized if getattr(self, "is_quantized", False): raise ValueError( "`.half()` is not supported for quantized model. Please use the model as it is, since the" " model has already...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
@classmethod def _load_pretrained_model( cls, model, state_dict: OrderedDict, resolved_archive_file, pretrained_model_name_or_path: Union[str, os.PathLike], ignore_mismatched_sizes: bool = False, ): # Retrieve missing & unexpected_keys model_state_...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
def _find_mismatched_keys( state_dict, model_state_dict, loaded_keys, ignore_mismatched_sizes, ): mismatched_keys = [] if ignore_mismatched_sizes: for checkpoint_key in loaded_keys: model_key = checkpoint...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
if state_dict is not None: # Whole checkpoint mismatched_keys = _find_mismatched_keys( state_dict, model_state_dict, original_loaded_keys, ignore_mismatched_sizes, ) error_msgs = _load_state_dict_into_model(m...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
if len(unexpected_keys) > 0: logger.warning( f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when" f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are" f" initializing {model.__cl...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
if len(missing_keys) > 0: logger.warning( f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at" f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably" " TRAIN this model on a...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated" for key, shape1, shape2 in mismatched_keys ] ) logger.warning( f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
return model, missing_keys, unexpected_keys, mismatched_keys, error_msgs @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...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
Returns: `List[str]`: List of modules that should not be split """ _no_split_modules = set() modules_to_check = [self] while len(modules_to_check) > 0: module = modules_to_check.pop(-1) # if the module does not appear in _no_split_modules, we also chec...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
return list(_no_split_modules)
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
@property def device(self) -> torch.device: """ `torch.device`: The device on which the module is (assuming that all the module parameters are on the same device). """ return get_parameter_device(self) @property def dtype(self) -> torch.dtype: """ `to...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
Returns: `int`: The number of parameters. Example: ```py from diffusers import UNet2DConditionModel model_id = "runwayml/stable-diffusion-v1-5" unet = UNet2DConditionModel.from_pretrained(model_id, subfolder="unet") unet.num_parameters(only_trainable=True) ...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
if exclude_embeddings: embedding_param_names = [ f"{name}.weight" for name, module_type in self.named_modules() if isinstance(module_type, nn.Embedding) ] total_parameters = [ parameter for name, parameter in self.named_parameters() if name not in embe...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
for param in total_parameters: if param.requires_grad or not only_trainable: # For 4bit models, we need to multiply the number of parameters by 2 as half of the parameters are # used for the 4bit quantization (uint8 tensors are stored) if is_loaded_in_4bit and...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
def get_memory_footprint(self, return_buffers=True): r""" Get the memory footprint of a model. This will return the memory footprint of the current model in bytes. Useful to benchmark the memory footprint of the current model and design some tests. Solution inspired from the PyTorch disc...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
Arguments: return_buffers (`bool`, *optional*, defaults to `True`): Whether to return the size of the buffer tensors in the computation of the memory footprint. Buffers are tensors that do not require gradients and not registered as parameters. E.g. mean and std in batch ...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
def recursive_find_attn_block(name, module): if hasattr(module, "_from_deprecated_attn_block") and module._from_deprecated_attn_block: deprecated_attention_block_paths.append(name) for sub_name, sub_module in module.named_children(): sub_name = sub_name if name =...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
# query -> to_q if f"{path}.query.weight" in state_dict: state_dict[f"{path}.to_q.weight"] = state_dict.pop(f"{path}.query.weight") if f"{path}.query.bias" in state_dict: state_dict[f"{path}.to_q.bias"] = state_dict.pop(f"{path}.query.bias") # key -> ...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
# proj_attn -> to_out.0 if f"{path}.proj_attn.weight" in state_dict: state_dict[f"{path}.to_out.0.weight"] = state_dict.pop(f"{path}.proj_attn.weight") if f"{path}.proj_attn.bias" in state_dict: state_dict[f"{path}.to_out.0.bias"] = state_dict.pop(f"{path}.proj_at...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
for module in deprecated_attention_block_modules: module.query = module.to_q module.key = module.to_k module.value = module.to_v module.proj_attn = module.to_out[0] # We don't _have_ to delete the old attributes, but it's helpful to ensure # that ...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
for sub_module in module.children(): recursive_find_attn_block(sub_module) recursive_find_attn_block(self) for module in deprecated_attention_block_modules: module.to_q = module.query module.to_k = module.key module.to_v = module.value mo...
906
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
class LegacyModelMixin(ModelMixin): r""" A subclass of `ModelMixin` to resolve class mapping from legacy classes (like `Transformer2DModel`) to more pipeline-specific classes (like `DiTTransformer2DModel`). """ @classmethod @validate_hf_hub_args def from_pretrained(cls, pretrained_model_nam...
907
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
# Load config if we don't provide a configuration config_path = pretrained_model_name_or_path user_agent = { "diffusers": __version__, "file_type": "model", "framework": "pytorch", } # load config config, _, _ = cls.load_config( c...
907
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/modeling_utils.py
class FlaxTimestepEmbedding(nn.Module): r""" Time step Embedding Module. Learns embeddings for input time steps. Args: time_embed_dim (`int`, *optional*, defaults to `32`): Time step embedding dimension. dtype (`jnp.dtype`, *optional*, defaults to `jnp.float32`): The...
908
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings_flax.py
class FlaxTimesteps(nn.Module): r""" Wrapper Module for sinusoidal Time step Embeddings as described in https://arxiv.org/abs/2006.11239 Args: dim (`int`, *optional*, defaults to `32`): Time step embedding dimension. flip_sin_to_cos (`bool`, *optional*, defaults to `False`): ...
909
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/embeddings_flax.py
class PatchedLoraProjection(torch.nn.Module): def __init__(self, regular_linear_layer, lora_scale=1, network_alpha=None, rank=4, dtype=None): deprecation_message = "Use of `PatchedLoraProjection` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`." deprecate("Patched...
910
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
# overwrite PyTorch's `state_dict` to be sure that only the 'regular_linear_layer' weights are saved # when saving the whole text encoder model and when LoRA is unloaded or fused def state_dict(self, *args, destination=None, prefix="", keep_vars=False): if self.lora_linear_layer is None: ret...
910
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
if self.lora_linear_layer.network_alpha is not None: w_up = w_up * self.lora_linear_layer.network_alpha / self.lora_linear_layer.rank fused_weight = w_orig + (lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0]) if safe_fusing and torch.isnan(fused_weight).any().item(): r...
910
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
def _unfuse_lora(self): if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None): return fused_weight = self.regular_linear_layer.weight.data dtype, device = fused_weight.dtype, fused_weight.device w_up = self.w_up.to(device=device).flo...
910
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
class LoRALinearLayer(nn.Module): r""" A linear layer that is used with LoRA. Parameters: in_features (`int`): Number of input features. out_features (`int`): Number of output features. rank (`int`, `optional`, defaults to 4): The rank of the LoRA...
911
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
def __init__( self, in_features: int, out_features: int, rank: int = 4, network_alpha: Optional[float] = None, device: Optional[Union[torch.device, str]] = None, dtype: Optional[torch.dtype] = None, ): super().__init__() deprecation_message = ...
911
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
self.down = nn.Linear(in_features, rank, bias=False, device=device, dtype=dtype) self.up = nn.Linear(rank, out_features, bias=False, device=device, dtype=dtype) # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script. # See https://github.com/darkstorm215...
911
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
return up_hidden_states.to(orig_dtype)
911
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
class LoRAConv2dLayer(nn.Module): r""" A convolutional layer that is used with LoRA.
912
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
Parameters: in_features (`int`): Number of input features. out_features (`int`): Number of output features. rank (`int`, `optional`, defaults to 4): The rank of the LoRA layer. kernel_size (`int` or `tuple` of two `int`, `optional`, defaults to 1): ...
912
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
def __init__( self, in_features: int, out_features: int, rank: int = 4, kernel_size: Union[int, Tuple[int, int]] = (1, 1), stride: Union[int, Tuple[int, int]] = (1, 1), padding: Union[int, Tuple[int, int], str] = 0, network_alpha: Optional[float] = None, ...
912
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
# This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script. # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning self.network_alpha = network_alpha self.rank = rank nn.init.normal_(self.down.we...
912
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
class LoRACompatibleConv(nn.Conv2d): """ A convolutional layer that can be used with LoRA. """ def __init__(self, *args, lora_layer: Optional[LoRAConv2dLayer] = None, **kwargs): deprecation_message = "Use of `LoRACompatibleConv` is deprecated. Please switch to PEFT backend by installing PEFT: `...
913
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
w_orig = self.weight.data.float() w_up = self.lora_layer.up.weight.data.float() w_down = self.lora_layer.down.weight.data.float() if self.lora_layer.network_alpha is not None: w_up = w_up * self.lora_layer.network_alpha / self.lora_layer.rank fusion = torch.mm(w_up.flatten(...
913
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
# offload the up and down matrices to CPU to not blow the memory self.w_up = w_up.cpu() self.w_down = w_down.cpu() self._lora_scale = lora_scale def _unfuse_lora(self): if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None): return...
913
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor: if self.padding_mode != "zeros": hidden_states = F.pad(hidden_states, self._reversed_padding_repeated_twice, mode=self.padding_mode) padding = (0, 0) else: padding = self.padding ...
913
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
class LoRACompatibleLinear(nn.Linear): """ A Linear layer that can be used with LoRA. """ def __init__(self, *args, lora_layer: Optional[LoRALinearLayer] = None, **kwargs): deprecation_message = "Use of `LoRACompatibleLinear` is deprecated. Please switch to PEFT backend by installing PEFT: `pip...
914
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
w_orig = self.weight.data.float() w_up = self.lora_layer.up.weight.data.float() w_down = self.lora_layer.down.weight.data.float() if self.lora_layer.network_alpha is not None: w_up = w_up * self.lora_layer.network_alpha / self.lora_layer.rank fused_weight = w_orig + (lora_s...
914
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
def _unfuse_lora(self): if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None): return fused_weight = self.weight.data dtype, device = fused_weight.dtype, fused_weight.device w_up = self.w_up.to(device=device).float() w_down =...
914
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/lora.py
class FlaxDecoderOutput(BaseOutput): """ Output of decoding method. Args: sample (`jnp.ndarray` of shape `(batch_size, num_channels, height, width)`): The decoded output sample from the last layer of the model. dtype (`jnp.dtype`, *optional*, defaults to `jnp.float32`): ...
915
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
class FlaxAutoencoderKLOutput(BaseOutput): """ Output of AutoencoderKL encoding method. Args: latent_dist (`FlaxDiagonalGaussianDistribution`): Encoded outputs of `Encoder` represented as the mean and logvar of `FlaxDiagonalGaussianDistribution`. `FlaxDiagonalGaussianDistrib...
916
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
class FlaxUpsample2D(nn.Module): """ Flax implementation of 2D Upsample layer Args: in_channels (`int`): Input channels dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32): Parameters `dtype` """ in_channels: int dtype: jnp.dtype = jnp.float32 ...
917
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
class FlaxDownsample2D(nn.Module): """ Flax implementation of 2D Downsample layer Args: in_channels (`int`): Input channels dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32): Parameters `dtype` """ in_channels: int dtype: jnp.dtype = jnp.floa...
918
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
class FlaxResnetBlock2D(nn.Module): """ Flax implementation of 2D Resnet Block. Args: in_channels (`int`): Input channels out_channels (`int`): Output channels dropout (:obj:`float`, *optional*, defaults to 0.0): Dropout rate groups (:obj:...
919
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
self.norm1 = nn.GroupNorm(num_groups=self.groups, epsilon=1e-6) self.conv1 = nn.Conv( out_channels, kernel_size=(3, 3), strides=(1, 1), padding=((1, 1), (1, 1)), dtype=self.dtype, ) self.norm2 = nn.GroupNorm(num_groups=self.groups, eps...
919
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
def __call__(self, hidden_states, deterministic=True): residual = hidden_states hidden_states = self.norm1(hidden_states) hidden_states = nn.swish(hidden_states) hidden_states = self.conv1(hidden_states) hidden_states = self.norm2(hidden_states) hidden_states = nn.swish(...
919
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
class FlaxAttentionBlock(nn.Module): r""" Flax Convolutional based multi-head attention block for diffusion-based VAE. Parameters: channels (:obj:`int`): Input channels num_head_channels (:obj:`int`, *optional*, defaults to `None`): Number of attention heads ...
920
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
self.group_norm = nn.GroupNorm(num_groups=self.num_groups, epsilon=1e-6) self.query, self.key, self.value = dense(), dense(), dense() self.proj_attn = dense() def transpose_for_scores(self, projection): new_projection_shape = projection.shape[:-1] + (self.num_heads, -1) # move heads...
920
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
# transpose query = self.transpose_for_scores(query) key = self.transpose_for_scores(key) value = self.transpose_for_scores(value) # compute attentions scale = 1 / math.sqrt(math.sqrt(self.channels / self.num_heads)) attn_weights = jnp.einsum("...qc,...kc->...qk", query ...
920
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
class FlaxDownEncoderBlock2D(nn.Module): r""" Flax Resnet blocks-based Encoder block for diffusion-based VAE. Parameters: in_channels (:obj:`int`): Input channels out_channels (:obj:`int`): Output channels dropout (:obj:`float`, *optional*, defaults to 0.0): ...
921
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
def setup(self): resnets = [] for i in range(self.num_layers): in_channels = self.in_channels if i == 0 else self.out_channels res_block = FlaxResnetBlock2D( in_channels=in_channels, out_channels=self.out_channels, dropout=self.dro...
921
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
class FlaxUpDecoderBlock2D(nn.Module): r""" Flax Resnet blocks-based Decoder block for diffusion-based VAE. Parameters: in_channels (:obj:`int`): Input channels out_channels (:obj:`int`): Output channels dropout (:obj:`float`, *optional*, defaults to 0.0): ...
922
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
def setup(self): resnets = [] for i in range(self.num_layers): in_channels = self.in_channels if i == 0 else self.out_channels res_block = FlaxResnetBlock2D( in_channels=in_channels, out_channels=self.out_channels, dropout=self.drop...
922
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
class FlaxUNetMidBlock2D(nn.Module): r""" Flax Unet Mid-Block module. Parameters: in_channels (:obj:`int`): Input channels dropout (:obj:`float`, *optional*, defaults to 0.0): Dropout rate num_layers (:obj:`int`, *optional*, defaults to 1): Number...
923
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
def setup(self): resnet_groups = self.resnet_groups if self.resnet_groups is not None else min(self.in_channels // 4, 32) # there is always at least one resnet resnets = [ FlaxResnetBlock2D( in_channels=self.in_channels, out_channels=self.in_channels,...
923
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
res_block = FlaxResnetBlock2D( in_channels=self.in_channels, out_channels=self.in_channels, dropout=self.dropout, groups=resnet_groups, dtype=self.dtype, ) resnets.append(res_block) self.resnets = resnets ...
923
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
class FlaxEncoder(nn.Module): r""" Flax Implementation of VAE Encoder. This model is a Flax Linen [flax.linen.Module](https://flax.readthedocs.io/en/latest/flax.linen.html#module) subclass. Use it as a regular Flax linen Module and refer to the Flax documentation for all matter related to general u...
924
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
Parameters: in_channels (:obj:`int`, *optional*, defaults to 3): Input channels out_channels (:obj:`int`, *optional*, defaults to 3): Output channels down_block_types (:obj:`Tuple[str]`, *optional*, defaults to `(DownEncoderBlock2D)`): DownEncoder block type ...
924
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
in_channels: int = 3 out_channels: int = 3 down_block_types: Tuple[str] = ("DownEncoderBlock2D",) block_out_channels: Tuple[int] = (64,) layers_per_block: int = 2 norm_num_groups: int = 32 act_fn: str = "silu" double_z: bool = False dtype: jnp.dtype = jnp.float32 def setup(self): ...
924
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
down_block = FlaxDownEncoderBlock2D( in_channels=input_channel, out_channels=output_channel, num_layers=self.layers_per_block, resnet_groups=self.norm_num_groups, add_downsample=not is_final_block, dtype=self.dtype, ...
924
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
# end conv_out_channels = 2 * self.out_channels if self.double_z else self.out_channels self.conv_norm_out = nn.GroupNorm(num_groups=self.norm_num_groups, epsilon=1e-6) self.conv_out = nn.Conv( conv_out_channels, kernel_size=(3, 3), strides=(1, 1), ...
924
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
class FlaxDecoder(nn.Module): r""" Flax Implementation of VAE Decoder. This model is a Flax Linen [flax.linen.Module](https://flax.readthedocs.io/en/latest/flax.linen.html#module) subclass. Use it as a regular Flax linen Module and refer to the Flax documentation for all matter related to general u...
925
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
Parameters: in_channels (:obj:`int`, *optional*, defaults to 3): Input channels out_channels (:obj:`int`, *optional*, defaults to 3): Output channels up_block_types (:obj:`Tuple[str]`, *optional*, defaults to `(UpDecoderBlock2D)`): UpDecoder block type ...
925
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
in_channels: int = 3 out_channels: int = 3 up_block_types: Tuple[str] = ("UpDecoderBlock2D",) block_out_channels: int = (64,) layers_per_block: int = 2 norm_num_groups: int = 32 act_fn: str = "silu" dtype: jnp.dtype = jnp.float32 def setup(self): block_out_channels = self.block_...
925
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
# upsampling reversed_block_out_channels = list(reversed(block_out_channels)) output_channel = reversed_block_out_channels[0] up_blocks = [] for i, _ in enumerate(self.up_block_types): prev_output_channel = output_channel output_channel = reversed_block_out_channe...
925
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
# end self.conv_norm_out = nn.GroupNorm(num_groups=self.norm_num_groups, epsilon=1e-6) self.conv_out = nn.Conv( self.out_channels, kernel_size=(3, 3), strides=(1, 1), padding=((1, 1), (1, 1)), dtype=self.dtype, ) def __call__(self,...
925
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
class FlaxDiagonalGaussianDistribution(object): def __init__(self, parameters, deterministic=False): # Last axis to account for channels-last self.mean, self.logvar = jnp.split(parameters, 2, axis=-1) self.logvar = jnp.clip(self.logvar, -30.0, 20.0) self.deterministic = deterministic...
926
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
def nll(self, sample, axis=[1, 2, 3]): if self.deterministic: return jnp.array([0.0]) logtwopi = jnp.log(2.0 * jnp.pi) return 0.5 * jnp.sum(logtwopi + self.logvar + jnp.square(sample - self.mean) / self.var, axis=axis) def mode(self): return self.mean
926
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
class FlaxAutoencoderKL(nn.Module, FlaxModelMixin, ConfigMixin): r""" Flax implementation of a VAE model with KL loss for decoding latent representations. This model inherits from [`FlaxModelMixin`]. Check the superclass documentation for it's generic methods implemented for all models (such as downloa...
927
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
- [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit) - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation) - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap) - [Paralle...
927
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
Parameters: in_channels (`int`, *optional*, defaults to 3): Number of channels in the input image. out_channels (`int`, *optional*, defaults to 3): Number of channels in the output. down_block_types (`Tuple[str]`, *optional*, defaults to `(DownEncoderBlock2D)`): ...
927
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
The number of groups for normalization. sample_size (`int`, *optional*, defaults to 32): Sample input size. scaling_factor (`float`, *optional*, defaults to 0.18215): The component-wise standard deviation of the trained latent space computed using the first batch of the ...
927
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
in_channels: int = 3 out_channels: int = 3 down_block_types: Tuple[str] = ("DownEncoderBlock2D",) up_block_types: Tuple[str] = ("UpDecoderBlock2D",) block_out_channels: Tuple[int] = (64,) layers_per_block: int = 1 act_fn: str = "silu" latent_channels: int = 4 norm_num_groups: int = 32 ...
927
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py
def setup(self): self.encoder = FlaxEncoder( in_channels=self.config.in_channels, out_channels=self.config.latent_channels, down_block_types=self.config.down_block_types, block_out_channels=self.config.block_out_channels, layers_per_block=self.config.l...
927
/Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/models/vae_flax.py