


import logging

import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.albert.modeling_albert import (
    ALBERT_INPUTS_DOCSTRING,
    ALBERT_START_DOCSTRING,
    AlbertModel,
    AlbertPreTrainedModel,
    AlbertTransformer,
)


__lowerCAmelCase     :			Any      =logging.getLogger(__name__)
class 	_lowercase				(      A__	):






				'''simple docstring'''



				def 		__magic_name__(	self      :Optional[int]      ,      lowerCAmelCase__      :Dict      ,      lowerCAmelCase__      :List[str]      ,      lowerCAmelCase__      :List[Any]=None      ,      lowerCAmelCase__      :Optional[Any]=None     )		->      List[Any]:
										if current_layer == 0:
																__SCREAMING_SNAKE_CASE						:					List[str]		      =		self.embedding_hidden_mapping_in(lowerCAmelCase__     )
										else:
																__SCREAMING_SNAKE_CASE						:					Tuple		      =		hidden_states[0]

										__SCREAMING_SNAKE_CASE						:					Tuple		      =		int(self.config.num_hidden_layers / self.config.num_hidden_groups     )

										# Index of the hidden group
										__SCREAMING_SNAKE_CASE						:					List[str]		      =		int(current_layer / (self.config.num_hidden_layers / self.config.num_hidden_groups)     )

										__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		self.albert_layer_groups[group_idx](
										    lowerCAmelCase__      ,      lowerCAmelCase__      ,      head_mask[group_idx * layers_per_group : (group_idx + 1) * layers_per_group]      ,      )
										__SCREAMING_SNAKE_CASE						:					Tuple		      =		layer_group_output[0]

										return (hidden_states,)




@add_start_docstrings(
    '''The bare ALBERT Model transformer with PABEE outputting raw hidden-states without any specific head on top.'''						,      A__						,      )
class 	_lowercase				(      A__	):






				'''simple docstring'''



				def __init__(	self      :int      ,      lowerCAmelCase__      :List[str]     )		->      List[Any]:
										super().__init__(lowerCAmelCase__     )

										__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		AlbertTransformerWithPabee(lowerCAmelCase__     )

										self.init_weights()
										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		0
										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		0
										__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		0

										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		0


				def 		__magic_name__(	self      :int      ,      lowerCAmelCase__      :Optional[int]     )		->      str:
										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		threshold


				def 		__magic_name__(	self      :List[Any]      ,      lowerCAmelCase__      :Optional[int]     )		->      List[Any]:
										__SCREAMING_SNAKE_CASE						:					Dict		      =		patience


				def 		__magic_name__(	self      :Union[str, Any]     )		->      str:
										__SCREAMING_SNAKE_CASE						:					Any		      =		0
										__SCREAMING_SNAKE_CASE						:					int		      =		0


				def 		__magic_name__(	self      :Optional[int]     )		->      Dict:
										__SCREAMING_SNAKE_CASE						:					List[Any]		      =		self.inference_layers_num / self.inference_instances_num
										__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		(
										    f'''*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up ='''
										    f''' {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***'''
										)
										print(lowerCAmelCase__     )



				@add_start_docstrings_to_model_forward(lowerCAmelCase__     )
				def 		__magic_name__(	self      :Dict      ,      lowerCAmelCase__      :List[str]=None      ,      lowerCAmelCase__      :List[str]=None      ,      lowerCAmelCase__      :Optional[Any]=None      ,      lowerCAmelCase__      :Any=None      ,      lowerCAmelCase__      :Dict=None      ,      lowerCAmelCase__      :Optional[int]=None      ,      lowerCAmelCase__      :str=None      ,      lowerCAmelCase__      :str=None      ,      lowerCAmelCase__      :str=False      ,      )		->      Union[str, Any]:

										if input_ids is not None and inputs_embeds is not None:
																raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time'''     )
										elif input_ids is not None:
																__SCREAMING_SNAKE_CASE						:					List[Any]		      =		input_ids.size()
										elif inputs_embeds is not None:
																__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		inputs_embeds.size()[:-1]
										else:
																raise ValueError('''You have to specify either input_ids or inputs_embeds'''     )

										__SCREAMING_SNAKE_CASE						:					List[str]		      =		input_ids.device if input_ids is not None else inputs_embeds.device

										if attention_mask is None:
																__SCREAMING_SNAKE_CASE						:					List[str]		      =		torch.ones(lowerCAmelCase__      ,      device=lowerCAmelCase__     )
										if token_type_ids is None:
																__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		torch.zeros(lowerCAmelCase__      ,      dtype=torch.long      ,      device=lowerCAmelCase__     )

										__SCREAMING_SNAKE_CASE						:					Any		      =		attention_mask.unsqueeze(1     ).unsqueeze(2     )
										__SCREAMING_SNAKE_CASE						:					Tuple		      =		extended_attention_mask.to(dtype=self.dtype     )  # fp16 compatibility
										__SCREAMING_SNAKE_CASE						:					Dict		      =		(1.0 - extended_attention_mask) * -10_000.0
										__SCREAMING_SNAKE_CASE						:					str		      =		self.get_head_mask(lowerCAmelCase__      ,      self.config.num_hidden_layers     )

										__SCREAMING_SNAKE_CASE						:					List[str]		      =		self.embeddings(
										    lowerCAmelCase__      ,      position_ids=lowerCAmelCase__      ,      token_type_ids=lowerCAmelCase__      ,      inputs_embeds=lowerCAmelCase__     )
										__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		embedding_output

										if self.training:
																__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		[]
																for i in range(self.config.num_hidden_layers     ):
																						__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		self.encoder.adaptive_forward(
																						    lowerCAmelCase__      ,      current_layer=lowerCAmelCase__      ,      attention_mask=lowerCAmelCase__      ,      head_mask=lowerCAmelCase__      ,      )

																						__SCREAMING_SNAKE_CASE						:					Any		      =		self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]     )     )
																						__SCREAMING_SNAKE_CASE						:					Tuple		      =		output_layers[i](output_dropout(lowerCAmelCase__     )     )
																						res.append(lowerCAmelCase__     )
										elif self.patience == 0:  # Use all layers for inference
																__SCREAMING_SNAKE_CASE						:					List[str]		      =		self.encoder(lowerCAmelCase__      ,      lowerCAmelCase__      ,      head_mask=lowerCAmelCase__     )
																__SCREAMING_SNAKE_CASE						:					List[Any]		      =		self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]     )     )
																__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		[output_layers[self.config.num_hidden_layers - 1](lowerCAmelCase__     )]
										else:
																__SCREAMING_SNAKE_CASE						:					List[str]		      =		0
																__SCREAMING_SNAKE_CASE						:					Any		      =		None
																__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		0
																for i in range(self.config.num_hidden_layers     ):
																						calculated_layer_num += 1
																						__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		self.encoder.adaptive_forward(
																						    lowerCAmelCase__      ,      current_layer=lowerCAmelCase__      ,      attention_mask=lowerCAmelCase__      ,      head_mask=lowerCAmelCase__      ,      )

																						__SCREAMING_SNAKE_CASE						:					List[str]		      =		self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]     )     )
																						__SCREAMING_SNAKE_CASE						:					str		      =		output_layers[i](lowerCAmelCase__     )
																						if regression:
																												__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		logits.detach()
																												if patient_result is not None:
																																		__SCREAMING_SNAKE_CASE						:					int		      =		patient_result.detach()
																												if (patient_result is not None) and torch.abs(patient_result - labels     ) < self.regression_threshold:
																																		patient_counter += 1
																												else:
																																		__SCREAMING_SNAKE_CASE						:					List[str]		      =		0
																						else:
																												__SCREAMING_SNAKE_CASE						:					List[str]		      =		logits.detach().argmax(dim=1     )
																												if patient_result is not None:
																																		__SCREAMING_SNAKE_CASE						:					List[str]		      =		patient_result.detach().argmax(dim=1     )
																												if (patient_result is not None) and torch.all(labels.eq(lowerCAmelCase__     )     ):
																																		patient_counter += 1
																												else:
																																		__SCREAMING_SNAKE_CASE						:					str		      =		0

																						__SCREAMING_SNAKE_CASE						:					str		      =		logits
																						if patient_counter == self.patience:
																												break
																__SCREAMING_SNAKE_CASE						:					List[str]		      =		[patient_result]
																self.inference_layers_num += calculated_layer_num
																self.inference_instances_num += 1

										return res




@add_start_docstrings(
    '''Albert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of
    the pooled output) e.g. for GLUE tasks. '''						,      A__						,      )
class 	_lowercase				(      A__	):






				'''simple docstring'''



				def __init__(	self      :List[Any]      ,      lowerCAmelCase__      :int     )		->      Optional[int]:
										super().__init__(lowerCAmelCase__     )
										__SCREAMING_SNAKE_CASE						:					Any		      =		config.num_labels

										__SCREAMING_SNAKE_CASE						:					str		      =		AlbertModelWithPabee(lowerCAmelCase__     )
										__SCREAMING_SNAKE_CASE						:					Tuple		      =		nn.Dropout(config.classifier_dropout_prob     )
										__SCREAMING_SNAKE_CASE						:					Dict		      =		nn.ModuleList(
										    [nn.Linear(config.hidden_size      ,      self.config.num_labels     ) for _ in range(config.num_hidden_layers     )]     )

										self.init_weights()



				@add_start_docstrings_to_model_forward(lowerCAmelCase__     )
				def 		__magic_name__(	self      :Optional[int]      ,      lowerCAmelCase__      :str=None      ,      lowerCAmelCase__      :List[str]=None      ,      lowerCAmelCase__      :Dict=None      ,      lowerCAmelCase__      :str=None      ,      lowerCAmelCase__      :Tuple=None      ,      lowerCAmelCase__      :int=None      ,      lowerCAmelCase__      :Any=None      ,      )		->      Dict:
										__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		self.albert(
										    input_ids=lowerCAmelCase__      ,      attention_mask=lowerCAmelCase__      ,      token_type_ids=lowerCAmelCase__      ,      position_ids=lowerCAmelCase__      ,      head_mask=lowerCAmelCase__      ,      inputs_embeds=lowerCAmelCase__      ,      output_dropout=self.dropout      ,      output_layers=self.classifiers      ,      regression=self.num_labels == 1      ,      )

										__SCREAMING_SNAKE_CASE						:					int		      =		(logits[-1],)

										if labels is not None:
																__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		None
																__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		0
																for ix, logits_item in enumerate(lowerCAmelCase__     ):
																						if self.num_labels == 1:
																												#  We are doing regression
																												__SCREAMING_SNAKE_CASE						:					str		      =		MSELoss()
																												__SCREAMING_SNAKE_CASE						:					List[Any]		      =		loss_fct(logits_item.view(-1     )      ,      labels.view(-1     )     )
																						else:
																												__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		CrossEntropyLoss()
																												__SCREAMING_SNAKE_CASE						:					List[Any]		      =		loss_fct(logits_item.view(-1      ,      self.num_labels     )      ,      labels.view(-1     )     )
																						if total_loss is None:
																												__SCREAMING_SNAKE_CASE						:					Dict		      =		loss
																						else:
																												total_loss += loss * (ix + 1)
																						total_weights += ix + 1
																__SCREAMING_SNAKE_CASE						:					Any		      =		(total_loss / total_weights,) + outputs

										return outputs




from typing import Any, Callable, Dict, List, Optional, Union

import PIL.Image
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionImgaImgPipeline,
    StableDiffusionInpaintPipelineLegacy,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.configuration_utils import FrozenDict
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import deprecate, logging


__lowerCAmelCase     :			Tuple      =logging.get_logger(__name__)  # pylint: disable=invalid-name
class 	_lowercase				(      A__	):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE__    :      Union[str, Any]      =		['''safety_checker''', '''feature_extractor''']


				def __init__(	self      :int      ,      lowerCAmelCase__      :AutoencoderKL      ,      lowerCAmelCase__      :CLIPTextModel      ,      lowerCAmelCase__      :CLIPTokenizer      ,      lowerCAmelCase__      :UNetaDConditionModel      ,      lowerCAmelCase__      :Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]      ,      lowerCAmelCase__      :StableDiffusionSafetyChecker      ,      lowerCAmelCase__      :CLIPImageProcessor      ,      lowerCAmelCase__      :bool = True      ,      )		->      List[Any]:
										super().__init__()
										if hasattr(scheduler.config      ,      '''steps_offset'''     ) and scheduler.config.steps_offset != 1:
																__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		(
																    f'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`'''
																    f''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure '''
																    '''to update the config accordingly as leaving `steps_offset` might led to incorrect results'''
																    ''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,'''
																    ''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`'''
																    ''' file'''
																)
																deprecate('''steps_offset!=1'''      ,      '''1.0.0'''      ,      lowerCAmelCase__      ,      standard_warn=lowerCAmelCase__     )
																__SCREAMING_SNAKE_CASE						:					Dict		      =		dict(scheduler.config     )
																__SCREAMING_SNAKE_CASE						:					Tuple		      =		1
																__SCREAMING_SNAKE_CASE						:					Dict		      =		FrozenDict(lowerCAmelCase__     )

										self.register_modules(
										    vae=lowerCAmelCase__      ,      text_encoder=lowerCAmelCase__      ,      tokenizer=lowerCAmelCase__      ,      unet=lowerCAmelCase__      ,      scheduler=lowerCAmelCase__      ,      safety_checker=lowerCAmelCase__      ,      feature_extractor=lowerCAmelCase__      ,      )
										self.register_to_config(requires_safety_checker=lowerCAmelCase__     )


				@property
				def 		__magic_name__(	self      :Union[str, Any]     )		->      Dict[str, Any]:
										return {k: getattr(self      ,      lowerCAmelCase__     ) for k in self.config.keys() if not k.startswith('''_'''     )}


				def 		__magic_name__(	self      :str      ,      lowerCAmelCase__      :Optional[Union[str, int]] = "auto"     )		->      str:
										if slice_size == "auto":
																# half the attention head size is usually a good trade-off between
																# speed and memory
																__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		self.unet.config.attention_head_dim // 2
										self.unet.set_attention_slice(lowerCAmelCase__     )


				def 		__magic_name__(	self      :Optional[int]     )		->      Union[str, Any]:
										self.enable_attention_slicing(lowerCAmelCase__     )


				@torch.no_grad()
				def 		__magic_name__(	self      :str      ,      lowerCAmelCase__      :Union[str, List[str]]      ,      lowerCAmelCase__      :Union[torch.FloatTensor, PIL.Image.Image]      ,      lowerCAmelCase__      :Union[torch.FloatTensor, PIL.Image.Image]      ,      lowerCAmelCase__      :float = 0.8      ,      lowerCAmelCase__      :Optional[int] = 50      ,      lowerCAmelCase__      :Optional[float] = 7.5      ,      lowerCAmelCase__      :Optional[Union[str, List[str]]] = None      ,      lowerCAmelCase__      :Optional[int] = 1      ,      lowerCAmelCase__      :Optional[float] = 0.0      ,      lowerCAmelCase__      :Optional[torch.Generator] = None      ,      lowerCAmelCase__      :Optional[str] = "pil"      ,      lowerCAmelCase__      :bool = True      ,      lowerCAmelCase__      :Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      lowerCAmelCase__      :int = 1      ,      )		->      Any:
										# For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
										return StableDiffusionInpaintPipelineLegacy(**self.components     )(
										    prompt=lowerCAmelCase__      ,      image=lowerCAmelCase__      ,      mask_image=lowerCAmelCase__      ,      strength=lowerCAmelCase__      ,      num_inference_steps=lowerCAmelCase__      ,      guidance_scale=lowerCAmelCase__      ,      negative_prompt=lowerCAmelCase__      ,      num_images_per_prompt=lowerCAmelCase__      ,      eta=lowerCAmelCase__      ,      generator=lowerCAmelCase__      ,      output_type=lowerCAmelCase__      ,      return_dict=lowerCAmelCase__      ,      callback=lowerCAmelCase__      ,      )


				@torch.no_grad()
				def 		__magic_name__(	self      :Dict      ,      lowerCAmelCase__      :Union[str, List[str]]      ,      lowerCAmelCase__      :Union[torch.FloatTensor, PIL.Image.Image]      ,      lowerCAmelCase__      :float = 0.8      ,      lowerCAmelCase__      :Optional[int] = 50      ,      lowerCAmelCase__      :Optional[float] = 7.5      ,      lowerCAmelCase__      :Optional[Union[str, List[str]]] = None      ,      lowerCAmelCase__      :Optional[int] = 1      ,      lowerCAmelCase__      :Optional[float] = 0.0      ,      lowerCAmelCase__      :Optional[torch.Generator] = None      ,      lowerCAmelCase__      :Optional[str] = "pil"      ,      lowerCAmelCase__      :bool = True      ,      lowerCAmelCase__      :Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      lowerCAmelCase__      :int = 1      ,      **lowerCAmelCase__      :Optional[Any]      ,      )		->      Dict:
										# For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
										return StableDiffusionImgaImgPipeline(**self.components     )(
										    prompt=lowerCAmelCase__      ,      image=lowerCAmelCase__      ,      strength=lowerCAmelCase__      ,      num_inference_steps=lowerCAmelCase__      ,      guidance_scale=lowerCAmelCase__      ,      negative_prompt=lowerCAmelCase__      ,      num_images_per_prompt=lowerCAmelCase__      ,      eta=lowerCAmelCase__      ,      generator=lowerCAmelCase__      ,      output_type=lowerCAmelCase__      ,      return_dict=lowerCAmelCase__      ,      callback=lowerCAmelCase__      ,      callback_steps=lowerCAmelCase__      ,      )



				@torch.no_grad()
				def 		__magic_name__(	self      :Tuple      ,      lowerCAmelCase__      :Union[str, List[str]]      ,      lowerCAmelCase__      :int = 512      ,      lowerCAmelCase__      :int = 512      ,      lowerCAmelCase__      :int = 50      ,      lowerCAmelCase__      :float = 7.5      ,      lowerCAmelCase__      :Optional[Union[str, List[str]]] = None      ,      lowerCAmelCase__      :Optional[int] = 1      ,      lowerCAmelCase__      :float = 0.0      ,      lowerCAmelCase__      :Optional[torch.Generator] = None      ,      lowerCAmelCase__      :Optional[torch.FloatTensor] = None      ,      lowerCAmelCase__      :Optional[str] = "pil"      ,      lowerCAmelCase__      :bool = True      ,      lowerCAmelCase__      :Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      lowerCAmelCase__      :int = 1      ,      )		->      Optional[int]:
										# For more information on how this function https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionPipeline
										return StableDiffusionPipeline(**self.components     )(
										    prompt=lowerCAmelCase__      ,      height=lowerCAmelCase__      ,      width=lowerCAmelCase__      ,      num_inference_steps=lowerCAmelCase__      ,      guidance_scale=lowerCAmelCase__      ,      negative_prompt=lowerCAmelCase__      ,      num_images_per_prompt=lowerCAmelCase__      ,      eta=lowerCAmelCase__      ,      generator=lowerCAmelCase__      ,      latents=lowerCAmelCase__      ,      output_type=lowerCAmelCase__      ,      return_dict=lowerCAmelCase__      ,      callback=lowerCAmelCase__      ,      callback_steps=lowerCAmelCase__      ,      )
