


'''simple docstring'''
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.bert.modeling_bert import (
    BERT_INPUTS_DOCSTRING,
    BERT_START_DOCSTRING,
    BertEmbeddings,
    BertLayer,
    BertPooler,
    BertPreTrainedModel,
)


def 			a      (			__a   )  ->	Any:



					'''simple docstring'''






					UpperCamelCase__   :str												= torch.exp(__a   )
					UpperCamelCase__   :Tuple												= torch.sum(__a ,					dim=1   )  # sum of exp(x_i)
					UpperCamelCase__   :Optional[Any]												= torch.sum(x * exp_x ,					dim=1   )  # sum of x_i * exp(x_i)
					return torch.log(__a   ) - B / A
class    lowercase	(							nn.Module					):

		"""simple docstring"""

		def __init__(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							super().__init__()
							UpperCamelCase__   :Dict												= config.output_attentions
							UpperCamelCase__   :Union[str, Any]												= config.output_hidden_states
							UpperCamelCase__   :List[str]												= nn.ModuleList([BertLayer(UpperCamelCase_							) for _ in range(config.num_hidden_layers							)]							)
							UpperCamelCase__   :int												= nn.ModuleList([BertHighway(UpperCamelCase_							) for _ in range(config.num_hidden_layers							)]							)

							UpperCamelCase__   :str												= [-1 for _ in range(config.num_hidden_layers							)]




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							if (type(UpperCamelCase_							) is float) or (type(UpperCamelCase_							) is int):
												for i in range(len(self.early_exit_entropy							)							):
																	UpperCamelCase__   :Union[str, Any]												= x
							else:
												UpperCamelCase__   :Optional[Any]												= x




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :List[str]												= pooler.state_dict()
							for highway in self.highway:
												for name, param in highway.pooler.state_dict().items():
																	param.copy_(loaded_model[name]							)




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   ):

							'''simple docstring'''


							UpperCamelCase__   :str												= ()
							UpperCamelCase__   :Optional[int]												= ()
							UpperCamelCase__   :Optional[int]												= ()
							for i, layer_module in enumerate(self.layer							):
												if self.output_hidden_states:
																	UpperCamelCase__   :Optional[int]												= all_hidden_states + (hidden_states,)

												UpperCamelCase__   :Dict												= layer_module(
												    UpperCamelCase_    ,   UpperCamelCase_    ,   head_mask[i]    ,   UpperCamelCase_    ,   UpperCamelCase_							)
												UpperCamelCase__   :str												= layer_outputs[0]

												if self.output_attentions:
																	UpperCamelCase__   :int												= all_attentions + (layer_outputs[1],)

												UpperCamelCase__   :List[Any]												= (hidden_states,)
												if self.output_hidden_states:
																	UpperCamelCase__   :Union[str, Any]												= current_outputs + (all_hidden_states,)
												if self.output_attentions:
																	UpperCamelCase__   :int												= current_outputs + (all_attentions,)

												UpperCamelCase__   :Optional[int]												= self.highway[i](UpperCamelCase_							)
												# logits, pooled_output

												if not self.training:
																	UpperCamelCase__   :List[str]												= highway_exit[0]
																	UpperCamelCase__   :List[Any]												= entropy(UpperCamelCase_							)
																	UpperCamelCase__   :Tuple												= highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
																	UpperCamelCase__   :int												= all_highway_exits + (highway_exit,)

																	if highway_entropy < self.early_exit_entropy[i]:
																						UpperCamelCase__   :str												= (highway_logits,) + current_outputs[1:] + (all_highway_exits,)
																						raise HighwayException(UpperCamelCase_    ,   i + 1							)
												else:
																	UpperCamelCase__   :int												= all_highway_exits + (highway_exit,)

        # Add last layer
							if self.output_hidden_states:
												UpperCamelCase__   :int												= all_hidden_states + (hidden_states,)

							UpperCamelCase__   :List[Any]												= (hidden_states,)
							if self.output_hidden_states:
												UpperCamelCase__   :Union[str, Any]												= outputs + (all_hidden_states,)
							if self.output_attentions:
												UpperCamelCase__   :int												= outputs + (all_attentions,)

							UpperCamelCase__   :Optional[Any]												= outputs + (all_highway_exits,)
							return outputs  # last-layer hidden state, (all hidden states), (all attentions), all highway exits



@add_start_docstrings(
    'The Bert Model transformer with early exiting (DeeBERT). '	,		A__	,		)
class    lowercase	(							A__					):

		"""simple docstring"""

		def __init__(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							super().__init__(UpperCamelCase_							)
							UpperCamelCase__   :Tuple												= config

							UpperCamelCase__   :Dict												= BertEmbeddings(UpperCamelCase_							)
							UpperCamelCase__   :Union[str, Any]												= DeeBertEncoder(UpperCamelCase_							)
							UpperCamelCase__   :str												= BertPooler(UpperCamelCase_							)

							self.init_weights()




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							self.encoder.init_highway_pooler(self.pooler							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							return self.embeddings.word_embeddings




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :Union[str, Any]												= value




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							for layer, heads in heads_to_prune.items():
												self.encoder.layer[layer].attention.prune_heads(UpperCamelCase_							)




		@add_start_docstrings_to_model_forward(UpperCamelCase_							)
		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   ):

							'''simple docstring'''


							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:
												UpperCamelCase__   :List[str]												= input_ids.size()
							elif inputs_embeds is not None:
												UpperCamelCase__   :int												= inputs_embeds.size()[:-1]
							else:
												raise ValueError('''You have to specify either input_ids or inputs_embeds'''							)

							UpperCamelCase__   :Optional[Any]												= input_ids.device if input_ids is not None else inputs_embeds.device

							if attention_mask is None:
												UpperCamelCase__   :str												= torch.ones(UpperCamelCase_    ,   device=UpperCamelCase_							)
							if encoder_attention_mask is None:
												UpperCamelCase__   :str												= torch.ones(UpperCamelCase_    ,   device=UpperCamelCase_							)
							if token_type_ids is None:
												UpperCamelCase__   :Optional[int]												= torch.zeros(UpperCamelCase_    ,   dtype=torch.long    ,   device=UpperCamelCase_							)

							# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
							# ourselves in which case we just need to make it broadcastable to all heads.
							UpperCamelCase__   :torch.Tensor												= self.get_extended_attention_mask(UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_							)

							# If a 2D ou 3D attention mask is provided for the cross-attention
							# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
							if encoder_attention_mask.dim() == 3:
												UpperCamelCase__   :Tuple												= encoder_attention_mask[:, None, :, :]
							if encoder_attention_mask.dim() == 2:
												UpperCamelCase__   :int												= encoder_attention_mask[:, None, None, :]

							UpperCamelCase__   :int												= encoder_extended_attention_mask.to(
							    dtype=next(self.parameters()							).dtype							)  # fp16 compatibility
							UpperCamelCase__   :str												= (1.0 - encoder_extended_attention_mask) * -10000.0

							# Prepare head mask if needed
							# 1.0 in head_mask indicate we keep the head
							# attention_probs has shape bsz x n_heads x N x N
							# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
							# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
							UpperCamelCase__   :Dict												= self.get_head_mask(UpperCamelCase_    ,   self.config.num_hidden_layers							)

							UpperCamelCase__   :List[str]												= self.embeddings(
							    input_ids=UpperCamelCase_    ,   position_ids=UpperCamelCase_    ,   token_type_ids=UpperCamelCase_    ,   inputs_embeds=UpperCamelCase_							)
							UpperCamelCase__   :Tuple												= self.encoder(
							    UpperCamelCase_    ,   attention_mask=UpperCamelCase_    ,   head_mask=UpperCamelCase_    ,   encoder_hidden_states=UpperCamelCase_    ,   encoder_attention_mask=UpperCamelCase_    ,   )
							UpperCamelCase__   :Any												= encoder_outputs[0]
							UpperCamelCase__   :Tuple												= self.pooler(UpperCamelCase_							)

							UpperCamelCase__   :List[str]												= (
							    sequence_output,
							    pooled_output,
							) + encoder_outputs[
							    1:
							]  # add hidden_states and attentions if they are here
							return outputs  # sequence_output, pooled_output, (hidden_states), (attentions), highway exits



class    lowercase	(							A__					):

		"""simple docstring"""

		def __init__(		self    ,   UpperCamelCase_    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :str												= message
							UpperCamelCase__   :Union[str, Any]												= exit_layer  # start from 1!



class    lowercase	(							nn.Module					):

		"""simple docstring"""

		def __init__(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							super().__init__()
							UpperCamelCase__   :Dict												= BertPooler(UpperCamelCase_							)
							UpperCamelCase__   :Tuple												= nn.Dropout(config.hidden_dropout_prob							)
							UpperCamelCase__   :Optional[int]												= nn.Linear(config.hidden_size    ,   config.num_labels							)




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :int												= encoder_outputs[0]
							UpperCamelCase__   :Optional[Any]												= self.pooler(UpperCamelCase_							)
							# "return" pooler_output

							# BertModel
							UpperCamelCase__   :Union[str, Any]												= (pooler_input, pooler_output) + encoder_outputs[1:]
							# "return" bmodel_output

							# Dropout and classification
							UpperCamelCase__   :Any												= bmodel_output[1]

							UpperCamelCase__   :Union[str, Any]												= self.dropout(UpperCamelCase_							)
							UpperCamelCase__   :List[Any]												= self.classifier(UpperCamelCase_							)

							return logits, pooled_output



@add_start_docstrings(
    'Bert Model (with early exiting - DeeBERT) with a classifier on top,\n    also takes care of multi-layer training. '	,		A__	,		)
class    lowercase	(							A__					):

		"""simple docstring"""

		def __init__(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							super().__init__(UpperCamelCase_							)
							UpperCamelCase__   :List[Any]												= config.num_labels
							UpperCamelCase__   :Tuple												= config.num_hidden_layers

							UpperCamelCase__   :Any												= DeeBertModel(UpperCamelCase_							)
							UpperCamelCase__   :Any												= nn.Dropout(config.hidden_dropout_prob							)
							UpperCamelCase__   :Optional[Any]												= nn.Linear(config.hidden_size    ,   self.config.num_labels							)

							self.init_weights()




		@add_start_docstrings_to_model_forward(UpperCamelCase_							)
		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=None    ,   UpperCamelCase_=-1    ,   UpperCamelCase_=False    ,   ):

							'''simple docstring'''


							UpperCamelCase__   :int												= self.num_layers
							try:
												UpperCamelCase__   :Optional[int]												= self.bert(
												    UpperCamelCase_    ,   attention_mask=UpperCamelCase_    ,   token_type_ids=UpperCamelCase_    ,   position_ids=UpperCamelCase_    ,   head_mask=UpperCamelCase_    ,   inputs_embeds=UpperCamelCase_    ,   )
												# sequence_output, pooled_output, (hidden_states), (attentions), highway exits

												UpperCamelCase__   :List[str]												= outputs[1]

												UpperCamelCase__   :int												= self.dropout(UpperCamelCase_							)
												UpperCamelCase__   :Any												= self.classifier(UpperCamelCase_							)
												UpperCamelCase__   :List[str]												= (logits,) + outputs[2:]  # add hidden states and attention if they are here
							except HighwayException as e:
												UpperCamelCase__   :Any												= e.message
												UpperCamelCase__   :Union[str, Any]												= e.exit_layer
												UpperCamelCase__   :str												= outputs[0]

							if not self.training:
												UpperCamelCase__   :Optional[Any]												= entropy(UpperCamelCase_							)
												UpperCamelCase__   :Dict												= []
												UpperCamelCase__   :int												= []
							if labels is not None:
												if self.num_labels == 1:
																	#  We are doing regression
																	UpperCamelCase__   :Union[str, Any]												= MSELoss()
																	UpperCamelCase__   :Dict												= loss_fct(logits.view(-1							)    ,   labels.view(-1							)							)
												else:
																	UpperCamelCase__   :Dict												= CrossEntropyLoss()
																	UpperCamelCase__   :Tuple												= loss_fct(logits.view(-1    ,   self.num_labels							)    ,   labels.view(-1							)							)

												# work with highway exits
												UpperCamelCase__   :Optional[Any]												= []
												for highway_exit in outputs[-1]:
																	UpperCamelCase__   :Any												= highway_exit[0]
																	if not self.training:
																						highway_logits_all.append(UpperCamelCase_							)
																						highway_entropy.append(highway_exit[2]							)
																	if self.num_labels == 1:
																						#  We are doing regression
																						UpperCamelCase__   :int												= MSELoss()
																						UpperCamelCase__   :List[str]												= loss_fct(highway_logits.view(-1							)    ,   labels.view(-1							)							)
																	else:
																						UpperCamelCase__   :Union[str, Any]												= CrossEntropyLoss()
																						UpperCamelCase__   :Any												= loss_fct(highway_logits.view(-1    ,   self.num_labels							)    ,   labels.view(-1							)							)
																	highway_losses.append(UpperCamelCase_							)

												if train_highway:
																	UpperCamelCase__   :Dict												= (sum(highway_losses[:-1]							),) + outputs
																	# exclude the final highway, of course
												else:
																	UpperCamelCase__   :Union[str, Any]												= (loss,) + outputs
							if not self.training:
												UpperCamelCase__   :Any												= outputs + ((original_entropy, highway_entropy), exit_layer)
												if output_layer >= 0:
																	UpperCamelCase__   :Optional[Any]												= (
																	    (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
																	)  # use the highway of the last layer

							return outputs  # (loss), logits, (hidden_states), (attentions), (highway_exits)



"""simple docstring"""







import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionImageVariationPipeline
from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device


a__				:							Tuple						=     False




class  UpperCamelCase_	( unittest.TestCase):

	"""simple docstring"""





	pass




@slow
@require_torch_gpu
class  UpperCamelCase_	( unittest.TestCase):

	"""simple docstring"""





	def   UpperCAmelCase_      ( self			:				int   )       ->	int:
						__SCREAMING_SNAKE_CASE						   =				VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion"   )
						pipe.to(UpperCAmelCase__   )
						pipe.set_progress_bar_config(disable=UpperCAmelCase__   )

						__SCREAMING_SNAKE_CASE						   =				load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"   )
						__SCREAMING_SNAKE_CASE						   =				torch.manual_seed(0   )
						__SCREAMING_SNAKE_CASE						   =				pipe(
						    image=UpperCAmelCase__			,			generator=UpperCAmelCase__			,			guidance_scale=7.5			,			num_inference_steps=5_0			,			output_type="numpy"			,			).images

						__SCREAMING_SNAKE_CASE						   =				image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

						assert image.shape == (1, 5_1_2, 5_1_2, 3)
						__SCREAMING_SNAKE_CASE						   =				np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945]   )

						assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1E-2
