


'''simple docstring'''
import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase__  =     logging.get_logger(__name__)

lowerCAmelCase__  =     {
    'facebook/hubert-base-ls960': 'https://huggingface.co/facebook/hubert-base-ls960/resolve/main/config.json',
    # See all Hubert models at https://huggingface.co/models?filter=hubert
}







class 					_A						(						UpperCamelCase							):



   '''simple docstring'''






   _lowercase    						= 'hubert'




   def __init__(	self	:					List[Any]					, lowerCamelCase	:					Dict=32					, lowerCamelCase	:					List[Any]=768					, lowerCamelCase	:					int=12					, lowerCamelCase	:					int=12					, lowerCamelCase	:					Union[str, Any]=3_072					, lowerCamelCase	:					str="gelu"					, lowerCamelCase	:					Optional[int]=0.1					, lowerCamelCase	:					Optional[int]=0.1					, lowerCamelCase	:					Tuple=0.1					, lowerCamelCase	:					List[str]=True					, lowerCamelCase	:					List[str]=0.0					, lowerCamelCase	:					List[Any]=0.1					, lowerCamelCase	:					List[Any]=0.1					, lowerCamelCase	:					List[Any]=0.02					, lowerCamelCase	:					Tuple=1e-5					, lowerCamelCase	:					Tuple="group"					, lowerCamelCase	:					Dict="gelu"					, lowerCamelCase	:					str=(512, 512, 512, 512, 512, 512, 512)					, lowerCamelCase	:					Union[str, Any]=(5, 2, 2, 2, 2, 2, 2)					, lowerCamelCase	:					List[Any]=(10, 3, 3, 3, 3, 2, 2)					, lowerCamelCase	:					Dict=False					, lowerCamelCase	:					Dict=128					, lowerCamelCase	:					Optional[int]=16					, lowerCamelCase	:					int=False					, lowerCamelCase	:					Any=True					, lowerCamelCase	:					Any=0.05					, lowerCamelCase	:					str=10					, lowerCamelCase	:					int=2					, lowerCamelCase	:					Optional[int]=0.0					, lowerCamelCase	:					Tuple=10					, lowerCamelCase	:					Optional[Any]=0					, lowerCamelCase	:					Dict="sum"					, lowerCamelCase	:					int=False					, lowerCamelCase	:					Any=False					, lowerCamelCase	:					Dict=256					, lowerCamelCase	:					List[Any]=0					, lowerCamelCase	:					str=1					, lowerCamelCase	:					str=2					, **lowerCamelCase	:					Tuple					, )->	Union[str, Any]:
          super().__init__(**lowerCamelCase					, pad_token_id=lowerCamelCase					, bos_token_id=lowerCamelCase					, eos_token_id=lowerCamelCase						)
          snake_case__					:	int          =					hidden_size
          snake_case__					:	Dict          =					feat_extract_norm
          snake_case__					:	List[str]          =					feat_extract_activation
          snake_case__					:	Optional[Any]          =					list(lowerCamelCase						)
          snake_case__					:	Optional[int]          =					list(lowerCamelCase						)
          snake_case__					:	Tuple          =					list(lowerCamelCase						)
          snake_case__					:	Optional[int]          =					conv_bias
          snake_case__					:	Tuple          =					num_conv_pos_embeddings
          snake_case__					:	Dict          =					num_conv_pos_embedding_groups
          snake_case__					:	Union[str, Any]          =					len(self.conv_dim						)
          snake_case__					:	Dict          =					num_hidden_layers
          snake_case__					:	Optional[int]          =					intermediate_size
          snake_case__					:	Dict          =					hidden_act
          snake_case__					:	Optional[int]          =					num_attention_heads
          snake_case__					:	Optional[Any]          =					hidden_dropout
          snake_case__					:	Dict          =					attention_dropout
          snake_case__					:	List[Any]          =					activation_dropout
          snake_case__					:	Tuple          =					feat_proj_layer_norm
          snake_case__					:	Union[str, Any]          =					feat_proj_dropout
          snake_case__					:	List[Any]          =					final_dropout
          snake_case__					:	int          =					layerdrop
          snake_case__					:	Union[str, Any]          =					layer_norm_eps
          snake_case__					:	int          =					initializer_range
          snake_case__					:	Union[str, Any]          =					vocab_size
          snake_case__					:	Optional[Any]          =					do_stable_layer_norm
          snake_case__					:	List[str]          =					use_weighted_layer_sum
          snake_case__					:	List[Any]          =					classifier_proj_size

          if (
              (len(self.conv_stride						) != self.num_feat_extract_layers)
              or (len(self.conv_kernel						) != self.num_feat_extract_layers)
              or (len(self.conv_dim						) != self.num_feat_extract_layers)
          ):
                 raise ValueError(
                     """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="""
                     """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="""
                     F""" {len(self.conv_dim						)}`, `len(config.conv_stride) = {len(self.conv_stride						)}`,"""
                     F""" `len(config.conv_kernel) = {len(self.conv_kernel						)}`."""						)

          # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
          snake_case__					:	List[Any]          =					apply_spec_augment
          snake_case__					:	Tuple          =					mask_time_prob
          snake_case__					:	Optional[int]          =					mask_time_length
          snake_case__					:	Dict          =					mask_time_min_masks
          snake_case__					:	List[str]          =					mask_feature_prob
          snake_case__					:	List[Any]          =					mask_feature_length
          snake_case__					:	Optional[int]          =					mask_feature_min_masks

          # ctc loss
          snake_case__					:	List[Any]          =					ctc_loss_reduction
          snake_case__					:	List[str]          =					ctc_zero_infinity




   @property
   def   __lowerCAmelCase						(	self	:					Union[str, Any]						)->	Dict:
          return functools.reduce(operator.mul					, self.conv_stride					, 1						)








'''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					, )




