


'''simple docstring'''
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__  =     logging.getLogger(__name__)







class 					_A						(						UpperCamelCase							):



   '''simple docstring'''






   def   __lowerCAmelCase						(	self	:					Optional[Any]					, lowerCamelCase	:					Optional[Any]					, lowerCamelCase	:					List[Any]					, lowerCamelCase	:					Optional[int]=None					, lowerCamelCase	:					Union[str, Any]=None						)->	Tuple:
          if current_layer == 0:
                 snake_case__					:	List[str]          =					self.embedding_hidden_mapping_in(lowerCamelCase						)
          else:
                 snake_case__					:	Tuple          =					hidden_states[0]

          snake_case__					:	Any          =					int(self.config.num_hidden_layers / self.config.num_hidden_groups						)

          # Index of the hidden group
          snake_case__					:	Tuple          =					int(current_layer / (self.config.num_hidden_layers / self.config.num_hidden_groups)						)

          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]					, )
          snake_case__					:	Optional[int]          =					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.'    ,  UpperCamelCase    ,  )
class 					_A						(						UpperCamelCase							):



   '''simple docstring'''






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

          snake_case__					:	Any          =					AlbertTransformerWithPabee(lowerCamelCase						)

          self.init_weights()
          snake_case__					:	str          =					0
          snake_case__					:	Optional[Any]          =					0
          snake_case__					:	Dict          =					0

          snake_case__					:	Any          =					0




   def   __lowerCAmelCase						(	self	:					Optional[int]					, lowerCamelCase	:					Any						)->	Union[str, Any]:
          snake_case__					:	List[str]          =					threshold




   def   __lowerCAmelCase						(	self	:					Union[str, Any]					, lowerCamelCase	:					Dict						)->	Tuple:
          snake_case__					:	Dict          =					patience




   def   __lowerCAmelCase						(	self	:					Union[str, Any]						)->	Tuple:
          snake_case__					:	Union[str, Any]          =					0
          snake_case__					:	List[Any]          =					0




   def   __lowerCAmelCase						(	self	:					Dict						)->	List[str]:
          snake_case__					:	Optional[int]          =					self.inference_layers_num / self.inference_instances_num
          snake_case__					:	Tuple          =					(
              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   __lowerCAmelCase						(	self	:					Tuple					, lowerCamelCase	:					Optional[int]=None					, lowerCamelCase	:					str=None					, lowerCamelCase	:					int=None					, lowerCamelCase	:					Any=None					, lowerCamelCase	:					Tuple=None					, lowerCamelCase	:					Any=None					, lowerCamelCase	:					List[str]=None					, lowerCamelCase	:					List[str]=None					, lowerCamelCase	:					int=False					, )->	str:

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

          snake_case__					:	Optional[int]          =					input_ids.device if input_ids is not None else inputs_embeds.device

          if attention_mask is None:
                 snake_case__					:	Union[str, Any]          =					torch.ones(lowerCamelCase					, device=lowerCamelCase						)
          if token_type_ids is None:
                 snake_case__					:	int          =					torch.zeros(lowerCamelCase					, dtype=torch.long					, device=lowerCamelCase						)

          snake_case__					:	Tuple          =					attention_mask.unsqueeze(1						).unsqueeze(2						)
          snake_case__					:	List[str]          =					extended_attention_mask.to(dtype=self.dtype						)  # fp16 compatibility
          snake_case__					:	Optional[int]          =					(1.0 - extended_attention_mask) * -10_000.0
          snake_case__					:	Tuple          =					self.get_head_mask(lowerCamelCase					, self.config.num_hidden_layers						)

          snake_case__					:	List[str]          =					self.embeddings(
              lowerCamelCase					, position_ids=lowerCamelCase					, token_type_ids=lowerCamelCase					, inputs_embeds=lowerCamelCase						)
          snake_case__					:	str          =					embedding_output

          if self.training:
                 snake_case__					:	int          =					[]
                 for i in range(self.config.num_hidden_layers						):
                        snake_case__					:	Any          =					self.encoder.adaptive_forward(
                            lowerCamelCase					, current_layer=lowerCamelCase					, attention_mask=lowerCamelCase					, head_mask=lowerCamelCase					, )

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

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

                        snake_case__					:	List[Any]          =					logits
                        if patient_counter == self.patience:
                               break
                 snake_case__					:	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\n    the pooled output) e.g. for GLUE tasks. '    ,  UpperCamelCase    ,  )
class 					_A						(						UpperCamelCase							):



   '''simple docstring'''






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

          snake_case__					:	Dict          =					AlbertModelWithPabee(lowerCamelCase						)
          snake_case__					:	str          =					nn.Dropout(config.classifier_dropout_prob						)
          snake_case__					:	Any          =					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   __lowerCAmelCase						(	self	:					int					, lowerCamelCase	:					Optional[int]=None					, lowerCamelCase	:					List[str]=None					, lowerCamelCase	:					Dict=None					, lowerCamelCase	:					str=None					, lowerCamelCase	:					List[str]=None					, lowerCamelCase	:					Tuple=None					, lowerCamelCase	:					Tuple=None					, )->	int:
          snake_case__					:	List[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					, )

          snake_case__					:	Tuple          =					(logits[-1],)

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

          return outputs








'''simple docstring'''
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device


if is_torch_available():
     import torch

     from transformers import XLMProphetNetForConditionalGeneration, XLMProphetNetTokenizer







@require_torch
class 					_A						(						unittest.TestCase							):



   '''simple docstring'''






   @slow
   def   __lowerCAmelCase						(	self	:					Tuple						)->	Optional[int]:
          snake_case__					:	Any          =					XLMProphetNetForConditionalGeneration.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased"""						)
          model.to(lowerCamelCase						)

          # encoder-decoder outputs
          snake_case__					:	Optional[int]          =					torch.tensor([[17, 96_208, 103_471, 2]]						).to(lowerCamelCase						)
          snake_case__					:	Optional[Any]          =					torch.tensor(
              [[2, 250, 9_953, 34, 69_489, 1_620, 32, 118_424, 624, 210, 105, 2_913, 1_032, 351]]						).to(lowerCamelCase						)
          snake_case__					:	Optional[Any]          =					model(
              input_ids=lowerCamelCase					, attention_mask=lowerCamelCase					, encoder_outputs=lowerCamelCase					, decoder_input_ids=lowerCamelCase						)
          snake_case__					:	List[Any]          =					output[0]
          snake_case__					:	Any          =					torch.Size((1, 14, 250_012)						)
          self.assertEqual(output_predited_logis.shape					, lowerCamelCase						)
          snake_case__					:	Optional[int]          =					torch.tensor(
              [[[-6.3_986, -8.2_391, 12.5_189], [-6.3_289, -8.0_864, 12.6_211], [-6.2_418, -8.0_445, 12.7_968]]]						).to(lowerCamelCase						)
          self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]					, lowerCamelCase					, atol=1e-4						)						)

          # encoder outputs
          snake_case__					:	Dict          =					model.prophetnet.encoder(lowerCamelCase						)[0]
          snake_case__					:	Optional[Any]          =					torch.tensor(
              [[[-1.4_260, -0.7_628, 0.8_453], [-1.4_719, -0.1_391, 0.7_807], [-1.7_678, 0.0_114, 0.4_646]]]						).to(lowerCamelCase						)
          snake_case__					:	str          =					torch.Size((1, 4, 1_024)						)
          self.assertEqual(encoder_outputs.shape					, lowerCamelCase						)
          self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3]					, lowerCamelCase					, atol=1e-4						)						)

          # decoder outputs
          snake_case__					:	int          =					model.prophetnet.decoder(
              lowerCamelCase					, encoder_hidden_states=lowerCamelCase					, )
          snake_case__					:	Any          =					decoder_outputs[1].view(1					, model.config.ngram					, 14					, -1						)
          snake_case__					:	Optional[Any]          =					model.lm_head(lowerCamelCase						)
          snake_case__					:	str          =					predicting_streams_logits[:, 0]
          self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3]					, lowerCamelCase					, atol=1e-4						)						)




   @slow
   def   __lowerCAmelCase						(	self	:					Union[str, Any]						)->	Optional[Any]:
          snake_case__					:	Tuple          =					XLMProphetNetForConditionalGeneration.from_pretrained(
              """microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""						)
          model.to(lowerCamelCase						)

          snake_case__					:	str          =					torch.tensor([[17, 96_208, 103_471, 2]]						).to(lowerCamelCase						)
          snake_case__					:	Union[str, Any]          =					torch.tensor(
              [[2, 250, 9_953, 34, 69_489, 1_620, 32, 118_424, 624, 210, 105, 2_913, 1_032, 351]]						).to(lowerCamelCase						)
          snake_case__					:	List[Any]          =					model(
              input_ids=lowerCamelCase					, attention_mask=lowerCamelCase					, encoder_outputs=lowerCamelCase					, decoder_input_ids=lowerCamelCase						)
          snake_case__					:	List[str]          =					output[0]
          snake_case__					:	Any          =					torch.Size((1, 14, 250_012)						)
          self.assertEqual(output_predited_logis.shape					, lowerCamelCase						)
          # compare the actual values for a slice.
          snake_case__					:	List[str]          =					torch.tensor(
              [[[-9.2_253, -9.7_173, -6.3_529], [-7.6_701, -9.0_145, -1.9_382], [-8.0_195, -7.0_004, -0.1_523]]]						).to(lowerCamelCase						)

          self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]					, lowerCamelCase					, atol=1e-4						)						)




   @slow
   def   __lowerCAmelCase						(	self	:					str						)->	str:
          snake_case__					:	Dict          =					XLMProphetNetForConditionalGeneration.from_pretrained(
              """microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""						)
          model.to(lowerCamelCase						)
          snake_case__					:	Optional[int]          =					512

          snake_case__					:	Any          =					XLMProphetNetTokenizer.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""						)

          snake_case__					:	Optional[int]          =					(
              """Microsoft Corporation intends to officially end free support for the Windows 7 operating system after"""
              """ January 14, 2020, according to the official portal of the organization. From that day, users of this"""
              """ system will not be able to receive security updates, which could make their computers vulnerable to"""
              """ cyber attacks."""
          )
          snake_case__					:	Union[str, Any]          =					(
              """орпорация Microsoft намерена официально прекратить бесплатную поддержку операционной системы Windows 7"""
              """ после 14 января 2020 года, сообщается на официальном портале организации . С указанного дня пользователи"""
              """ этой системы не смогут получать обновления безопасности, из-за чего их компьютеры могут стать уязвимыми"""
              """ к кибератакам."""
          )
          snake_case__					:	int          =					(
              """根据该组织的官方门户网站，微软公司打算在2020年1月14日之后正式终止对Windows 7操作系统的免费支持。从那时起，该系统的用户将无法接收安全更新，这可能会使他们的计算机容易受到网络攻击。"""
          )

          snake_case__					:	int          =					tokenizer(
              [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE]					, padding=lowerCamelCase					, max_length=255					, return_tensors="""pt"""						).input_ids
          snake_case__					:	Optional[int]          =					input_ids.to(lowerCamelCase						)

          snake_case__					:	Optional[Any]          =					model.generate(
              lowerCamelCase					, num_beams=10					, length_penalty=1.0					, no_repeat_ngram_size=3					, early_stopping=lowerCamelCase						)
          snake_case__					:	Union[str, Any]          =					[tokenizer.decode(lowerCamelCase					, skip_special_tokens=lowerCamelCase						) for g in summary_ids]
          snake_case__					:	Optional[Any]          =					"""Microsoft to end Windows 7 free support after January 14, 2020"""
          snake_case__					:	Dict          =					"""Microsoft намерена прекратить бесплатную поддержку Windows 7 после 14 января 2020 года"""
          snake_case__					:	Optional[int]          =					"""微软打算终止对Windows 7操作系统的免费支持"""
          self.assertListEqual(
              [EXPECTED_TITLE_EN, EXPECTED_TITLE_RU, EXPECTED_TITLE_ZH]					, lowerCamelCase					, )

          snake_case__					:	Optional[int]          =					model.generate(
              lowerCamelCase					, num_beams=1					, length_penalty=1.0					, no_repeat_ngram_size=3					, early_stopping=lowerCamelCase						)
          snake_case__					:	Tuple          =					[
              tokenizer.convert_ids_to_tokens(lowerCamelCase					, skip_special_tokens=lowerCamelCase						) for g in summary_ids_beama
          ]
          snake_case__					:	Any          =					"""▁Microsoft ▁to ▁end ▁free ▁support ▁for ▁Windows ▁7""".split(""" """						)
          snake_case__					:	Union[str, Any]          =					"""▁Microsoft ▁намерен а ▁прекрати ть ▁бес плат ную ▁поддержку ▁Windows ▁7 ▁после ▁14 ▁января ▁2020 ▁года""".split(
              """ """						)
          snake_case__					:	Tuple          =					"""微软 公司 打算 终止 对 Windows ▁7 操作 系统的 免费 支持""".split(""" """						)
          self.assertListEqual(
              [EXPECTED_TITLE_EN_BEAM1_TOK, EXPECTED_TITLE_RU_BEAM1_TOK, EXPECTED_TITLE_ZH_BEAM1_TOK]					, lowerCamelCase					, )




