
import collections
import inspect
import unittest

from transformers import SwinvaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch
     from torch import nn

     from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel
     from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor




class 					_SCREAMING_SNAKE_CASE  :
      def __init__(			self		,	lowerCamelCase		,	lowerCamelCase=13		,	lowerCamelCase=32		,	lowerCamelCase=2		,	lowerCamelCase=3		,	lowerCamelCase=16		,	lowerCamelCase=[1, 2, 1]		,	lowerCamelCase=[2, 2, 4]		,	lowerCamelCase=2		,	lowerCamelCase=2.0		,	lowerCamelCase=True		,	lowerCamelCase=0.0		,	lowerCamelCase=0.0		,	lowerCamelCase=0.1		,	lowerCamelCase="gelu"		,	lowerCamelCase=False		,	lowerCamelCase=True		,	lowerCamelCase=0.0_2		,	lowerCamelCase=1e-5		,	lowerCamelCase=True		,	lowerCamelCase=None		,	lowerCamelCase=True		,	lowerCamelCase=10		,	lowerCamelCase=8		,	):
          snake_case__						=				parent
          snake_case__						=				batch_size
          snake_case__						=				image_size
          snake_case__						=				patch_size
          snake_case__						=				num_channels
          snake_case__						=				embed_dim
          snake_case__						=				depths
          snake_case__						=				num_heads
          snake_case__						=				window_size
          snake_case__						=				mlp_ratio
          snake_case__						=				qkv_bias
          snake_case__						=				hidden_dropout_prob
          snake_case__						=				attention_probs_dropout_prob
          snake_case__						=				drop_path_rate
          snake_case__						=				hidden_act
          snake_case__						=				use_absolute_embeddings
          snake_case__						=				patch_norm
          snake_case__						=				layer_norm_eps
          snake_case__						=				initializer_range
          snake_case__						=				is_training
          snake_case__						=				scope
          snake_case__						=				use_labels
          snake_case__						=				type_sequence_label_size
          snake_case__						=				encoder_stride
      def A_			(			self ):
          snake_case__						=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

          snake_case__						=				None
          if self.use_labels:
              snake_case__						=				ids_tensor([self.batch_size]		,	self.type_sequence_label_size )

          snake_case__						=				self.get_config()

          return config, pixel_values, labels
      def A_			(			self ):
          return SwinvaConfig(
              image_size=self.image_size		,	patch_size=self.patch_size		,	num_channels=self.num_channels		,	embed_dim=self.embed_dim		,	depths=self.depths		,	num_heads=self.num_heads		,	window_size=self.window_size		,	mlp_ratio=self.mlp_ratio		,	qkv_bias=self.qkv_bias		,	hidden_dropout_prob=self.hidden_dropout_prob		,	attention_probs_dropout_prob=self.attention_probs_dropout_prob		,	drop_path_rate=self.drop_path_rate		,	hidden_act=self.hidden_act		,	use_absolute_embeddings=self.use_absolute_embeddings		,	path_norm=self.patch_norm		,	layer_norm_eps=self.layer_norm_eps		,	initializer_range=self.initializer_range		,	encoder_stride=self.encoder_stride		,	)
      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase ):
          snake_case__						=				SwinvaModel(config=lowerCamelCase )
          model.to(lowerCamelCase )
          model.eval()
          snake_case__						=				model(lowerCamelCase )

          snake_case__						=				((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
          snake_case__						=				int(config.embed_dim * 2 ** (len(config.depths ) - 1) )

          self.parent.assertEqual(result.last_hidden_state.shape		,	(self.batch_size, expected_seq_len, expected_dim) )
      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase ):
          snake_case__						=				SwinvaForMaskedImageModeling(config=lowerCamelCase )
          model.to(lowerCamelCase )
          model.eval()
          snake_case__						=				model(lowerCamelCase )
          self.parent.assertEqual(
              result.logits.shape		,	(self.batch_size, self.num_channels, self.image_size, self.image_size) )

          # test greyscale images
          snake_case__						=				1
          snake_case__						=				SwinvaForMaskedImageModeling(lowerCamelCase )
          model.to(lowerCamelCase )
          model.eval()

          snake_case__						=				floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
          snake_case__						=				model(lowerCamelCase )
          self.parent.assertEqual(result.logits.shape		,	(self.batch_size, 1, self.image_size, self.image_size) )
      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase ):
          snake_case__						=				self.type_sequence_label_size
          snake_case__						=				SwinvaForImageClassification(lowerCamelCase )
          model.to(lowerCamelCase )
          model.eval()
          snake_case__						=				model(lowerCamelCase		,	labels=lowerCamelCase )
          self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.type_sequence_label_size) )



      def A_			(			self ):
          snake_case__						=				self.prepare_config_and_inputs()
          snake_case__						=				config_and_inputs
          snake_case__						=				{'''pixel_values''': pixel_values}
          return config, inputs_dict





@require_torch
class 					_SCREAMING_SNAKE_CASE  (      __A       ,					__A       ,					unittest.TestCase ):
      _A						:		List[str]    	=     (
          (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
      )
      _A						:		List[str]    	=     (
          {'feature-extraction': SwinvaModel, 'image-classification': SwinvaForImageClassification}
          if is_torch_available()
          else {}
      )

      _A						:		Optional[Any]    	=     False
      _A						:		Optional[Any]    	=     False
      _A						:		Union[str, Any]    	=     False
      _A						:		List[str]    	=     False
      def A_			(			self ):
          snake_case__						=				SwinvaModelTester(self )
          snake_case__						=				ConfigTester(self		,	config_class=lowerCamelCase		,	embed_dim=37 )
      def A_			(			self ):
          self.config_tester.create_and_test_config_to_json_string()
          self.config_tester.create_and_test_config_to_json_file()
          self.config_tester.create_and_test_config_from_and_save_pretrained()
          self.config_tester.create_and_test_config_with_num_labels()
          self.config_tester.check_config_can_be_init_without_params()
          self.config_tester.check_config_arguments_init()
      def A_			(			self ):
          snake_case__						=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowerCamelCase )
      @unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0." )
      def A_			(			self ):
          pass
      @unittest.skip(reason="Swinv2 does not use inputs_embeds" )
      def A_			(			self ):
          pass
      def A_			(			self ):
          snake_case__						=				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              snake_case__						=				model_class(lowerCamelCase )
              self.assertIsInstance(model.get_input_embeddings()		,	(nn.Module) )
              snake_case__						=				model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(lowerCamelCase		,	nn.Linear ) )
      def A_			(			self ):
          snake_case__						=				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              snake_case__						=				model_class(lowerCamelCase )
              snake_case__						=				inspect.signature(model.forward )
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              snake_case__						=				[*signature.parameters.keys()]

              snake_case__						=				['''pixel_values''']
              self.assertListEqual(arg_names[:1]		,	lowerCamelCase )
      def A_			(			self ):
          snake_case__						=				self.model_tester.prepare_config_and_inputs_for_common()
          snake_case__						=				True

          for model_class in self.all_model_classes:
              snake_case__						=				True
              snake_case__						=				False
              snake_case__						=				True
              snake_case__						=				model_class(lowerCamelCase )
              model.to(lowerCamelCase )
              model.eval()
              with torch.no_grad():
                  snake_case__						=				model(**self._prepare_for_class(lowerCamelCase		,	lowerCamelCase ) )
              snake_case__						=				outputs.attentions
              snake_case__						=				len(self.model_tester.depths )
              self.assertEqual(len(lowerCamelCase )		,	lowerCamelCase )

              # check that output_attentions also work using config
              del inputs_dict["output_attentions"]
              snake_case__						=				True
              snake_case__						=				config.window_size**2
              snake_case__						=				model_class(lowerCamelCase )
              model.to(lowerCamelCase )
              model.eval()
              with torch.no_grad():
                  snake_case__						=				model(**self._prepare_for_class(lowerCamelCase		,	lowerCamelCase ) )
              snake_case__						=				outputs.attentions
              self.assertEqual(len(lowerCamelCase )		,	lowerCamelCase )

              self.assertListEqual(
                  list(attentions[0].shape[-3:] )		,	[self.model_tester.num_heads[0], window_size_squared, window_size_squared]		,	)
              snake_case__						=				len(lowerCamelCase )

              # Check attention is always last and order is fine
              snake_case__						=				True
              snake_case__						=				True
              snake_case__						=				model_class(lowerCamelCase )
              model.to(lowerCamelCase )
              model.eval()
              with torch.no_grad():
                  snake_case__						=				model(**self._prepare_for_class(lowerCamelCase		,	lowerCamelCase ) )

              if hasattr(self.model_tester		,	"num_hidden_states_types" ):
                  snake_case__						=				self.model_tester.num_hidden_states_types
              else:
                  # also another +1 for reshaped_hidden_states
                  snake_case__						=				2
              self.assertEqual(out_len + added_hidden_states		,	len(lowerCamelCase ) )

              snake_case__						=				outputs.attentions

              self.assertEqual(len(lowerCamelCase )		,	lowerCamelCase )

              self.assertListEqual(
                  list(self_attentions[0].shape[-3:] )		,	[self.model_tester.num_heads[0], window_size_squared, window_size_squared]		,	)
      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase ):
          snake_case__						=				model_class(lowerCamelCase )
          model.to(lowerCamelCase )
          model.eval()

          with torch.no_grad():
              snake_case__						=				model(**self._prepare_for_class(lowerCamelCase		,	lowerCamelCase ) )

          snake_case__						=				outputs.hidden_states

          snake_case__						=				getattr(
              self.model_tester		,	"expected_num_hidden_layers"		,	len(self.model_tester.depths ) + 1 )
          self.assertEqual(len(lowerCamelCase )		,	lowerCamelCase )

          # Swinv2 has a different seq_length
          snake_case__						=				(
              config.patch_size
              if isinstance(config.patch_size		,	collections.abc.Iterable )
              else (config.patch_size, config.patch_size)
          )

          snake_case__						=				(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

          self.assertListEqual(
              list(hidden_states[0].shape[-2:] )		,	[num_patches, self.model_tester.embed_dim]		,	)

          snake_case__						=				outputs.reshaped_hidden_states
          self.assertEqual(len(lowerCamelCase )		,	lowerCamelCase )

          snake_case__						=				reshaped_hidden_states[0].shape
          snake_case__						=				(
              reshaped_hidden_states[0].view(lowerCamelCase		,	lowerCamelCase		,	height * width ).permute(0		,	2		,	1 )
          )
          self.assertListEqual(
              list(reshaped_hidden_states.shape[-2:] )		,	[num_patches, self.model_tester.embed_dim]		,	)
      def A_			(			self ):
          snake_case__						=				self.model_tester.prepare_config_and_inputs_for_common()

          snake_case__						=				(
              self.model_tester.image_size
              if isinstance(self.model_tester.image_size		,	collections.abc.Iterable )
              else (self.model_tester.image_size, self.model_tester.image_size)
          )

          for model_class in self.all_model_classes:
              snake_case__						=				True
              self.check_hidden_states_output(lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase )

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              snake_case__						=				True

              self.check_hidden_states_output(lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase )
      def A_			(			self ):
          snake_case__						=				self.model_tester.prepare_config_and_inputs_for_common()
          snake_case__						=				3

          snake_case__						=				(
              self.model_tester.image_size
              if isinstance(self.model_tester.image_size		,	collections.abc.Iterable )
              else (self.model_tester.image_size, self.model_tester.image_size)
          )
          snake_case__						=				(
              config.patch_size
              if isinstance(config.patch_size		,	collections.abc.Iterable )
              else (config.patch_size, config.patch_size)
          )

          snake_case__						=				image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
          snake_case__						=				image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

          for model_class in self.all_model_classes:
              snake_case__						=				True
              self.check_hidden_states_output(lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	(padded_height, padded_width) )

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              snake_case__						=				True
              self.check_hidden_states_output(lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase		,	(padded_height, padded_width) )
      def A_			(			self ):
          snake_case__						=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase )
      def A_			(			self ):
          snake_case__						=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowerCamelCase )
      @slow
      def A_			(			self ):

          for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              snake_case__						=				SwinvaModel.from_pretrained(lowerCamelCase )
              self.assertIsNotNone(lowerCamelCase )



      def A_			(			self ):
          snake_case__						=				self.model_tester.prepare_config_and_inputs_for_common()

          snake_case__						=				_config_zero_init(lowerCamelCase )
          for model_class in self.all_model_classes:
              snake_case__						=				model_class(config=lowerCamelCase )
              for name, param in model.named_parameters():
                  if "embeddings" not in name and "logit_scale" not in name and param.requires_grad:
                      self.assertIn(
                          ((param.data.mean() * 1e9).round() / 1e9).item()		,	[0.0, 1.0]		,	msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""		,	)





@require_vision
@require_torch
class 					_SCREAMING_SNAKE_CASE  (      unittest.TestCase ):
      @cached_property
      def A_			(			self ):
          return (
              AutoImageProcessor.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256" )
              if is_vision_available()
              else None
          )



      @slow
      def A_			(			self ):
          snake_case__						=				SwinvaForImageClassification.from_pretrained("microsoft/swinv2-tiny-patch4-window8-256" ).to(
              lowerCamelCase )
          snake_case__						=				self.default_image_processor

          snake_case__						=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
          snake_case__						=				image_processor(images=lowerCamelCase		,	return_tensors="pt" ).to(lowerCamelCase )

          # forward pass
          with torch.no_grad():
              snake_case__						=				model(**lowerCamelCase )

          # verify the logits
          snake_case__						=				torch.Size((1, 10_00) )
          self.assertEqual(outputs.logits.shape		,	lowerCamelCase )
          snake_case__						=				torch.tensor([-0.3_9_4_7, -0.4_3_0_6, 0.0_0_2_6] ).to(lowerCamelCase )
          self.assertTrue(torch.allclose(outputs.logits[0, :3]		,	lowerCamelCase		,	atol=1e-4 ) )


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 	SCREAMING_SNAKE_CASE__    (      __lowerCAmelCase							):
    snake_case__						=				torch.exp(__lowerCAmelCase							)
    snake_case__						=				torch.sum(__lowerCAmelCase    ,		dim=1							)  # sum of exp(x_i)
    snake_case__						=				torch.sum(x * exp_x    ,		dim=1							)  # sum of x_i * exp(x_i)
    return torch.log(__lowerCAmelCase							) - B / A




class 					_SCREAMING_SNAKE_CASE  (      nn.Module ):
      def __init__(			self		,	lowerCamelCase ):
          super().__init__()
          snake_case__						=				config.output_attentions
          snake_case__						=				config.output_hidden_states
          snake_case__						=				nn.ModuleList([BertLayer(lowerCamelCase ) for _ in range(config.num_hidden_layers )] )
          snake_case__						=				nn.ModuleList([BertHighway(lowerCamelCase ) for _ in range(config.num_hidden_layers )] )

          snake_case__						=				[-1 for _ in range(config.num_hidden_layers )]
      def A_			(			self		,	lowerCamelCase ):
          if (type(lowerCamelCase ) is float) or (type(lowerCamelCase ) is int):
              for i in range(len(self.early_exit_entropy ) ):
                  snake_case__						=				x
          else:
              snake_case__						=				x
      def A_			(			self		,	lowerCamelCase ):
          snake_case__						=				pooler.state_dict()
          for highway in self.highway:
              for name, param in highway.pooler.state_dict().items():
                  param.copy_(loaded_model[name] )



      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	):
          snake_case__						=				()
          snake_case__						=				()
          snake_case__						=				()
          for i, layer_module in enumerate(self.layer ):
              if self.output_hidden_states:
                  snake_case__						=				all_hidden_states + (hidden_states,)

              snake_case__						=				layer_module(
                  lowerCamelCase		,	lowerCamelCase		,	head_mask[i]		,	lowerCamelCase		,	lowerCamelCase )
              snake_case__						=				layer_outputs[0]

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

              snake_case__						=				(hidden_states,)
              if self.output_hidden_states:
                  snake_case__						=				current_outputs + (all_hidden_states,)
              if self.output_attentions:
                  snake_case__						=				current_outputs + (all_attentions,)

              snake_case__						=				self.highway[i](lowerCamelCase )
              # logits, pooled_output

              if not self.training:
                  snake_case__						=				highway_exit[0]
                  snake_case__						=				entropy(lowerCamelCase )
                  snake_case__						=				highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
                  snake_case__						=				all_highway_exits + (highway_exit,)

                  if highway_entropy < self.early_exit_entropy[i]:
                      snake_case__						=				(highway_logits,) + current_outputs[1:] + (all_highway_exits,)
                      raise HighwayException(lowerCamelCase		,	i + 1 )
              else:
                  snake_case__						=				all_highway_exits + (highway_exit,)

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

          snake_case__						=				(hidden_states,)
          if self.output_hidden_states:
              snake_case__						=				outputs + (all_hidden_states,)
          if self.output_attentions:
              snake_case__						=				outputs + (all_attentions,)

          snake_case__						=				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). '       ,					__UpperCamelCase       ,					)
class 					_SCREAMING_SNAKE_CASE  (      __UpperCamelCase ):
      def __init__(			self		,	lowerCamelCase ):
          super().__init__(lowerCamelCase )
          snake_case__						=				config

          snake_case__						=				BertEmbeddings(lowerCamelCase )
          snake_case__						=				DeeBertEncoder(lowerCamelCase )
          snake_case__						=				BertPooler(lowerCamelCase )

          self.init_weights()
      def A_			(			self ):
          self.encoder.init_highway_pooler(self.pooler )
      def A_			(			self ):
          return self.embeddings.word_embeddings
      def A_			(			self		,	lowerCamelCase ):
          snake_case__						=				value
      def A_			(			self		,	lowerCamelCase ):
          for layer, heads in heads_to_prune.items():
              self.encoder.layer[layer].attention.prune_heads(lowerCamelCase )



      @add_start_docstrings_to_model_forward(lowerCamelCase )
      def A_			(			self		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	):
          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:
              snake_case__						=				input_ids.size()
          elif inputs_embeds is not None:
              snake_case__						=				inputs_embeds.size()[:-1]
          else:
              raise ValueError("You have to specify either input_ids or inputs_embeds" )

          snake_case__						=				input_ids.device if input_ids is not None else inputs_embeds.device

          if attention_mask is None:
              snake_case__						=				torch.ones(lowerCamelCase		,	device=lowerCamelCase )
          if encoder_attention_mask is None:
              snake_case__						=				torch.ones(lowerCamelCase		,	device=lowerCamelCase )
          if token_type_ids is None:
              snake_case__						=				torch.zeros(lowerCamelCase		,	dtype=torch.long		,	device=lowerCamelCase )

          # 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.
          snake_case__						=				self.get_extended_attention_mask(lowerCamelCase		,	lowerCamelCase		,	lowerCamelCase )

          # 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:
              snake_case__						=				encoder_attention_mask[:, None, :, :]
          if encoder_attention_mask.dim() == 2:
              snake_case__						=				encoder_attention_mask[:, None, None, :]

          snake_case__						=				encoder_extended_attention_mask.to(
              dtype=next(self.parameters() ).dtype )  # fp16 compatibility
          snake_case__						=				(1.0 - encoder_extended_attention_mask) * -1_0_0_0_0.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]
          snake_case__						=				self.get_head_mask(lowerCamelCase		,	self.config.num_hidden_layers )

          snake_case__						=				self.embeddings(
              input_ids=lowerCamelCase		,	position_ids=lowerCamelCase		,	token_type_ids=lowerCamelCase		,	inputs_embeds=lowerCamelCase )
          snake_case__						=				self.encoder(
              lowerCamelCase		,	attention_mask=lowerCamelCase		,	head_mask=lowerCamelCase		,	encoder_hidden_states=lowerCamelCase		,	encoder_attention_mask=lowerCamelCase		,	)
          snake_case__						=				encoder_outputs[0]
          snake_case__						=				self.pooler(lowerCamelCase )

          snake_case__						=				(
              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 					_SCREAMING_SNAKE_CASE  (      __UpperCamelCase ):
      def __init__(			self		,	lowerCamelCase		,	lowerCamelCase ):
          snake_case__						=				message
          snake_case__						=				exit_layer  # start from 1!





class 					_SCREAMING_SNAKE_CASE  (      nn.Module ):
      def __init__(			self		,	lowerCamelCase ):
          super().__init__()
          snake_case__						=				BertPooler(lowerCamelCase )
          snake_case__						=				nn.Dropout(config.hidden_dropout_prob )
          snake_case__						=				nn.Linear(config.hidden_size		,	config.num_labels )



      def A_			(			self		,	lowerCamelCase ):
          # Pooler
          snake_case__						=				encoder_outputs[0]
          snake_case__						=				self.pooler(lowerCamelCase )
          # "return" pooler_output

          # BertModel
          snake_case__						=				(pooler_input, pooler_output) + encoder_outputs[1:]
          # "return" bmodel_output

          # Dropout and classification
          snake_case__						=				bmodel_output[1]

          snake_case__						=				self.dropout(lowerCamelCase )
          snake_case__						=				self.classifier(lowerCamelCase )

          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. '       ,					__UpperCamelCase       ,					)
class 					_SCREAMING_SNAKE_CASE  (      __UpperCamelCase ):
      def __init__(			self		,	lowerCamelCase ):
          super().__init__(lowerCamelCase )
          snake_case__						=				config.num_labels
          snake_case__						=				config.num_hidden_layers

          snake_case__						=				DeeBertModel(lowerCamelCase )
          snake_case__						=				nn.Dropout(config.hidden_dropout_prob )
          snake_case__						=				nn.Linear(config.hidden_size		,	self.config.num_labels )

          self.init_weights()



      @add_start_docstrings_to_model_forward(lowerCamelCase )
      def A_			(			self		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=-1		,	lowerCamelCase=False		,	):
          snake_case__						=				self.num_layers
          try:
              snake_case__						=				self.bert(
                  lowerCamelCase		,	attention_mask=lowerCamelCase		,	token_type_ids=lowerCamelCase		,	position_ids=lowerCamelCase		,	head_mask=lowerCamelCase		,	inputs_embeds=lowerCamelCase		,	)
              # sequence_output, pooled_output, (hidden_states), (attentions), highway exits

              snake_case__						=				outputs[1]

              snake_case__						=				self.dropout(lowerCamelCase )
              snake_case__						=				self.classifier(lowerCamelCase )
              snake_case__						=				(logits,) + outputs[2:]  # add hidden states and attention if they are here
          except HighwayException as e:
              snake_case__						=				e.message
              snake_case__						=				e.exit_layer
              snake_case__						=				outputs[0]

          if not self.training:
              snake_case__						=				entropy(lowerCamelCase )
              snake_case__						=				[]
              snake_case__						=				[]
          if labels is not None:
              if self.num_labels == 1:
                  #  We are doing regression
                  snake_case__						=				MSELoss()
                  snake_case__						=				loss_fct(logits.view(-1 )		,	labels.view(-1 ) )
              else:
                  snake_case__						=				CrossEntropyLoss()
                  snake_case__						=				loss_fct(logits.view(-1		,	self.num_labels )		,	labels.view(-1 ) )

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

              if train_highway:
                  snake_case__						=				(sum(highway_losses[:-1] ),) + outputs
                  # exclude the final highway, of course
              else:
                  snake_case__						=				(loss,) + outputs
          if not self.training:
              snake_case__						=				outputs + ((original_entropy, highway_entropy), exit_layer)
              if output_layer >= 0:
                  snake_case__						=				(
                      (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)



