






'''simple docstring'''
import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor
from transformers.utils import logging


logging.set_verbosity_info()
a_					=	logging.get_logger(__name__)





def 	_a(					UpperCamelCase__			:  str							):




						'''simple docstring'''






						SCREAMING_SNAKE_CASE__       :			Optional[int]													=YolosConfig()

						# size of the architecture
						if "yolos_ti" in yolos_name:
												SCREAMING_SNAKE_CASE__       :			List[str]													=1_9_2
												SCREAMING_SNAKE_CASE__       :			Optional[Any]													=7_6_8
												SCREAMING_SNAKE_CASE__       :			Optional[Any]													=1_2
												SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=3
												SCREAMING_SNAKE_CASE__       :			List[str]													=[8_0_0, 1_3_3_3]
												SCREAMING_SNAKE_CASE__       :			List[Any]													=False
						elif yolos_name == "yolos_s_dWr":
												SCREAMING_SNAKE_CASE__       :			str													=3_3_0
												SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=1_4
												SCREAMING_SNAKE_CASE__       :			Optional[Any]													=6
												SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=1_3_2_0
						elif "yolos_s" in yolos_name:
												SCREAMING_SNAKE_CASE__       :			Optional[int]													=3_8_4
												SCREAMING_SNAKE_CASE__       :			Tuple													=1_5_3_6
												SCREAMING_SNAKE_CASE__       :			List[Any]													=1_2
												SCREAMING_SNAKE_CASE__       :			Optional[int]													=6
						elif "yolos_b" in yolos_name:
												SCREAMING_SNAKE_CASE__       :			Optional[int]													=[8_0_0, 1_3_4_4]

						SCREAMING_SNAKE_CASE__       :			int													=9_1
						SCREAMING_SNAKE_CASE__       :			Tuple													='''huggingface/label-files'''
						SCREAMING_SNAKE_CASE__       :			Union[str, Any]													='''coco-detection-id2label.json'''
						SCREAMING_SNAKE_CASE__       :			Optional[int]													=json.load(open(hf_hub_download(UpperCamelCase__,		UpperCamelCase__,		repo_type='''dataset'''							),		'''r'''							)							)
						SCREAMING_SNAKE_CASE__       :			Any													={int(UpperCamelCase__							): v for k, v in idalabel.items()}
						SCREAMING_SNAKE_CASE__       :			Any													=idalabel
						SCREAMING_SNAKE_CASE__       :			Dict													={v: k for k, v in idalabel.items()}

						return config





def 	_a(					UpperCamelCase__			:  dict,		UpperCamelCase__			:  YolosConfig,		UpperCamelCase__			:  bool = False							):




						'''simple docstring'''






						for i in range(config.num_hidden_layers							):
												# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
												SCREAMING_SNAKE_CASE__       :			str													=state_dict.pop(f"blocks.{i}.attn.qkv.weight"							)
												SCREAMING_SNAKE_CASE__       :			Optional[int]													=state_dict.pop(f"blocks.{i}.attn.qkv.bias"							)
												# next, add query, keys and values (in that order) to the state dict
												SCREAMING_SNAKE_CASE__       :			str													=in_proj_weight[: config.hidden_size, :]
												SCREAMING_SNAKE_CASE__       :			Dict													=in_proj_bias[: config.hidden_size]
												SCREAMING_SNAKE_CASE__       :			str													=in_proj_weight[
												    config.hidden_size : config.hidden_size * 2, :
												]
												SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=in_proj_bias[
												    config.hidden_size : config.hidden_size * 2
												]
												SCREAMING_SNAKE_CASE__       :			int													=in_proj_weight[-config.hidden_size :, :]
												SCREAMING_SNAKE_CASE__       :			Tuple													=in_proj_bias[-config.hidden_size :]





def 	_a(					UpperCamelCase__			:  str							):




						'''simple docstring'''






						if "backbone" in name:
												SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=name.replace('''backbone''',		'''vit'''							)
						if "cls_token" in name:
												SCREAMING_SNAKE_CASE__       :			List[str]													=name.replace('''cls_token''',		'''embeddings.cls_token'''							)
						if "det_token" in name:
												SCREAMING_SNAKE_CASE__       :			Tuple													=name.replace('''det_token''',		'''embeddings.detection_tokens'''							)
						if "mid_pos_embed" in name:
												SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=name.replace('''mid_pos_embed''',		'''encoder.mid_position_embeddings'''							)
						if "pos_embed" in name:
												SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=name.replace('''pos_embed''',		'''embeddings.position_embeddings'''							)
						if "patch_embed.proj" in name:
												SCREAMING_SNAKE_CASE__       :			Optional[Any]													=name.replace('''patch_embed.proj''',		'''embeddings.patch_embeddings.projection'''							)
						if "blocks" in name:
												SCREAMING_SNAKE_CASE__       :			Dict													=name.replace('''blocks''',		'''encoder.layer'''							)
						if "attn.proj" in name:
												SCREAMING_SNAKE_CASE__       :			List[Any]													=name.replace('''attn.proj''',		'''attention.output.dense'''							)
						if "attn" in name:
												SCREAMING_SNAKE_CASE__       :			List[Any]													=name.replace('''attn''',		'''attention.self'''							)
						if "norm1" in name:
												SCREAMING_SNAKE_CASE__       :			Dict													=name.replace('''norm1''',		'''layernorm_before'''							)
						if "norm2" in name:
												SCREAMING_SNAKE_CASE__       :			List[Any]													=name.replace('''norm2''',		'''layernorm_after'''							)
						if "mlp.fc1" in name:
												SCREAMING_SNAKE_CASE__       :			List[str]													=name.replace('''mlp.fc1''',		'''intermediate.dense'''							)
						if "mlp.fc2" in name:
												SCREAMING_SNAKE_CASE__       :			Optional[int]													=name.replace('''mlp.fc2''',		'''output.dense'''							)
						if "class_embed" in name:
												SCREAMING_SNAKE_CASE__       :			Any													=name.replace('''class_embed''',		'''class_labels_classifier'''							)
						if "bbox_embed" in name:
												SCREAMING_SNAKE_CASE__       :			List[str]													=name.replace('''bbox_embed''',		'''bbox_predictor'''							)
						if "vit.norm" in name:
												SCREAMING_SNAKE_CASE__       :			Tuple													=name.replace('''vit.norm''',		'''vit.layernorm'''							)

						return name





def 	_a(					UpperCamelCase__			:  dict,		UpperCamelCase__			:  YolosForObjectDetection							):




						'''simple docstring'''






						for key in orig_state_dict.copy().keys():
												SCREAMING_SNAKE_CASE__       :			Optional[int]													=orig_state_dict.pop(UpperCamelCase__							)

												if "qkv" in key:
																		SCREAMING_SNAKE_CASE__       :			str													=key.split('''.'''							)
																		SCREAMING_SNAKE_CASE__       :			Tuple													=int(key_split[2]							)
																		SCREAMING_SNAKE_CASE__       :			Any													=model.vit.encoder.layer[layer_num].attention.attention.all_head_size
																		if "weight" in key:
																								SCREAMING_SNAKE_CASE__       :			str													=val[:dim, :]
																								SCREAMING_SNAKE_CASE__       :			int													=val[
																								    dim : dim * 2, :
																								]
																								SCREAMING_SNAKE_CASE__       :			Optional[Any]													=val[-dim:, :]
																		else:
																								SCREAMING_SNAKE_CASE__       :			int													=val[:dim]
																								SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=val[dim : dim * 2]
																								SCREAMING_SNAKE_CASE__       :			str													=val[-dim:]
												else:
																		SCREAMING_SNAKE_CASE__       :			Optional[Any]													=val

						return orig_state_dict





def 	_a(					):




						'''simple docstring'''






						SCREAMING_SNAKE_CASE__       :			Tuple													='''http://images.cocodataset.org/val2017/000000039769.jpg'''
						SCREAMING_SNAKE_CASE__       :			Any													=Image.open(requests.get(UpperCamelCase__,		stream=UpperCamelCase__							).raw							)
						return im





@torch.no_grad()
def 	_a(					UpperCamelCase__			:  str,		UpperCamelCase__			:  str,		UpperCamelCase__			:  str,		UpperCamelCase__			:  bool = False							):




						'''simple docstring'''






						SCREAMING_SNAKE_CASE__       :			List[Any]													=get_yolos_config(UpperCamelCase__							)

						# load original state_dict
						SCREAMING_SNAKE_CASE__       :			Optional[Any]													=torch.load(UpperCamelCase__,		map_location='''cpu'''							)['''model''']

						# load 🤗 model
						SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=YolosForObjectDetection(UpperCamelCase__							)
						model.eval()
						SCREAMING_SNAKE_CASE__       :			Dict													=convert_state_dict(UpperCamelCase__,		UpperCamelCase__							)
						model.load_state_dict(UpperCamelCase__							)

						# Check outputs on an image, prepared by YolosImageProcessor
						SCREAMING_SNAKE_CASE__       :			List[str]													=8_0_0 if yolos_name != '''yolos_ti''' else 5_1_2
						SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=YolosImageProcessor(format='''coco_detection''',		size=UpperCamelCase__							)
						SCREAMING_SNAKE_CASE__       :			str													=image_processor(images=prepare_img(),		return_tensors='''pt'''							)
						SCREAMING_SNAKE_CASE__       :			List[str]													=model(**UpperCamelCase__							)
						SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=outputs.logits, outputs.pred_boxes

						SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			str													=None, None
						if yolos_name == "yolos_ti":
												SCREAMING_SNAKE_CASE__       :			Any													=torch.tensor(
												    [[-3_9.5_0_2_2, -1_1.9_8_2_0, -1_7.6_8_8_8], [-2_9.9_5_7_4, -9.9_7_6_9, -1_7.7_6_9_1], [-4_2.3_2_8_1, -2_0.7_2_0_0, -3_0.6_2_9_4]]							)
												SCREAMING_SNAKE_CASE__       :			Optional[Any]													=torch.tensor(
												    [[0.4_0_2_1, 0.0_8_3_6, 0.7_9_7_9], [0.0_1_8_4, 0.2_6_0_9, 0.0_3_6_4], [0.1_7_8_1, 0.2_0_0_4, 0.2_0_9_5]]							)
						elif yolos_name == "yolos_s_200_pre":
												SCREAMING_SNAKE_CASE__       :			Optional[int]													=torch.tensor(
												    [[-2_4.0_2_4_8, -1_0.3_0_2_4, -1_4.8_2_9_0], [-4_2.0_3_9_2, -1_6.8_2_0_0, -2_7.4_3_3_4], [-2_7.2_7_4_3, -1_1.8_1_5_4, -1_8.7_1_4_8]]							)
												SCREAMING_SNAKE_CASE__       :			Optional[int]													=torch.tensor(
												    [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]]							)
						elif yolos_name == "yolos_s_300_pre":
												SCREAMING_SNAKE_CASE__       :			Dict													=torch.tensor(
												    [[-3_6.2_2_2_0, -1_4.4_3_8_5, -2_3.5_4_5_7], [-3_5.6_9_7_0, -1_4.7_5_8_3, -2_1.3_9_3_5], [-3_1.5_9_3_9, -1_3.6_0_4_2, -1_6.8_0_4_9]]							)
												SCREAMING_SNAKE_CASE__       :			Optional[Any]													=torch.tensor(
												    [[0.7_6_1_4, 0.2_3_1_6, 0.4_7_2_8], [0.7_1_6_8, 0.4_4_9_5, 0.3_8_5_5], [0.4_9_9_6, 0.1_4_6_6, 0.9_9_9_6]]							)
						elif yolos_name == "yolos_s_dWr":
												SCREAMING_SNAKE_CASE__       :			int													=torch.tensor(
												    [[-4_2.8_6_6_8, -2_4.1_0_4_9, -4_1.1_6_9_0], [-3_4.7_4_5_6, -1_4.1_2_7_4, -2_4.9_1_9_4], [-3_3.7_8_9_8, -1_2.1_9_4_6, -2_5.6_4_9_5]]							)
												SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=torch.tensor(
												    [[0.5_5_8_7, 0.2_7_7_3, 0.0_6_0_5], [0.5_0_0_4, 0.3_0_1_4, 0.9_9_9_4], [0.4_9_9_9, 0.1_5_4_8, 0.9_9_9_4]]							)
						elif yolos_name == "yolos_base":
												SCREAMING_SNAKE_CASE__       :			Any													=torch.tensor(
												    [[-4_0.6_0_6_4, -2_4.3_0_8_4, -3_2.6_4_4_7], [-5_5.1_9_9_0, -3_0.7_7_1_9, -3_5.5_8_7_7], [-5_1.4_3_1_1, -3_3.3_5_0_7, -3_5.6_4_6_2]]							)
												SCREAMING_SNAKE_CASE__       :			str													=torch.tensor(
												    [[0.5_5_5_5, 0.2_7_9_4, 0.0_6_5_5], [0.9_0_4_9, 0.2_6_6_4, 0.1_8_9_4], [0.9_1_8_3, 0.1_9_8_4, 0.1_6_3_5]]							)
						else:
												raise ValueError(f"Unknown yolos_name: {yolos_name}"							)

						assert torch.allclose(logits[0, :3, :3],		UpperCamelCase__,		atol=1e-4							)
						assert torch.allclose(pred_boxes[0, :3, :3],		UpperCamelCase__,		atol=1e-4							)

						Path(UpperCamelCase__							).mkdir(exist_ok=UpperCamelCase__							)
						print(f"Saving model {yolos_name} to {pytorch_dump_folder_path}"							)
						model.save_pretrained(UpperCamelCase__							)
						print(f"Saving image processor to {pytorch_dump_folder_path}"							)
						image_processor.save_pretrained(UpperCamelCase__							)

						if push_to_hub:
												SCREAMING_SNAKE_CASE__       :			Tuple													={
												    '''yolos_ti''': '''yolos-tiny''',
												    '''yolos_s_200_pre''': '''yolos-small''',
												    '''yolos_s_300_pre''': '''yolos-small-300''',
												    '''yolos_s_dWr''': '''yolos-small-dwr''',
												    '''yolos_base''': '''yolos-base''',
												}

												print('''Pushing to the hub...'''							)
												SCREAMING_SNAKE_CASE__       :			Any													=model_mapping[yolos_name]
												image_processor.push_to_hub(UpperCamelCase__,		organization='''hustvl'''							)
												model.push_to_hub(UpperCamelCase__,		organization='''hustvl'''							)


if __name__ == "__main__":
		a_					=	argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    '--yolos_name',
		    default='yolos_s_200_pre',
		    type=str,
		    help=(
		        'Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\','
		        ' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.'
		    ),
		)
		parser.add_argument(
		    '--checkpoint_path', default=None, type=str, help='Path to the original state dict (.pth file).'
		)
		parser.add_argument(
		    '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
		)
		parser.add_argument(
		    '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
		)

		a_					=	parser.parse_args()
		convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)







'''simple docstring'''
from __future__ import annotations

import unittest

from transformers import AutoTokenizer, PegasusConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel






@require_tf
class        __SCREAMING_SNAKE_CASE :
 snake_case_												=							PegasusConfig
 snake_case_												=							{}
 snake_case_												=							"""gelu"""




 def __init__( self		:							int   , __lowercase		:							Optional[Any]   , __lowercase		:							int=13   , __lowercase		:							List[str]=7   , __lowercase		:							Dict=True   , __lowercase		:							Tuple=False   , __lowercase		:							Optional[Any]=99   , __lowercase		:							str=32   , __lowercase		:							List[str]=2   , __lowercase		:							str=4   , __lowercase		:							Optional[int]=37   , __lowercase		:							List[Any]=0.1   , __lowercase		:							List[Any]=0.1   , __lowercase		:							List[Any]=40   , __lowercase		:							str=2   , __lowercase		:							List[Any]=1   , __lowercase		:							Optional[Any]=0   , )		->  Tuple:
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=parent
       SCREAMING_SNAKE_CASE__       :			List[Any]													=batch_size
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=seq_length
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=is_training
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=use_labels
       SCREAMING_SNAKE_CASE__       :			str													=vocab_size
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=hidden_size
       SCREAMING_SNAKE_CASE__       :			List[str]													=num_hidden_layers
       SCREAMING_SNAKE_CASE__       :			int													=num_attention_heads
       SCREAMING_SNAKE_CASE__       :			List[str]													=intermediate_size

       SCREAMING_SNAKE_CASE__       :			List[Any]													=hidden_dropout_prob
       SCREAMING_SNAKE_CASE__       :			List[Any]													=attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE__       :			List[Any]													=max_position_embeddings
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=eos_token_id
       SCREAMING_SNAKE_CASE__       :			Any													=pad_token_id
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=bos_token_id




 def        __magic_name__		( self		:							Any )		->  str:
       SCREAMING_SNAKE_CASE__       :			List[str]													=ids_tensor([self.batch_size, self.seq_length - 1]   , self.vocab_size )
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size )   , 1 )
       SCREAMING_SNAKE_CASE__       :			Any													=tf.concat([input_ids, eos_tensor]   , axis=1 )

       SCREAMING_SNAKE_CASE__       :			Dict													=ids_tensor([self.batch_size, self.seq_length]   , self.vocab_size )

       SCREAMING_SNAKE_CASE__       :			Optional[int]													=self.config_cls(
           vocab_size=self.vocab_size   , d_model=self.hidden_size   , encoder_layers=self.num_hidden_layers   , decoder_layers=self.num_hidden_layers   , encoder_attention_heads=self.num_attention_heads   , decoder_attention_heads=self.num_attention_heads   , encoder_ffn_dim=self.intermediate_size   , decoder_ffn_dim=self.intermediate_size   , dropout=self.hidden_dropout_prob   , attention_dropout=self.attention_probs_dropout_prob   , max_position_embeddings=self.max_position_embeddings   , eos_token_ids=[2]   , bos_token_id=self.bos_token_id   , pad_token_id=self.pad_token_id   , decoder_start_token_id=self.pad_token_id   , **self.config_updates   , )
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=prepare_pegasus_inputs_dict(__lowercase   , __lowercase   , __lowercase )
       return config, inputs_dict




 def        __magic_name__		( self		:							Optional[int]   , __lowercase		:							List[str]   , __lowercase		:							Optional[int] )		->  Tuple:
       SCREAMING_SNAKE_CASE__       :			List[Any]													=TFPegasusModel(config=__lowercase ).get_decoder()
       SCREAMING_SNAKE_CASE__       :			List[str]													=inputs_dict['''input_ids''']

       SCREAMING_SNAKE_CASE__       :			Tuple													=input_ids[:1, :]
       SCREAMING_SNAKE_CASE__       :			Tuple													=inputs_dict['''attention_mask'''][:1, :]
       SCREAMING_SNAKE_CASE__       :			Tuple													=inputs_dict['''head_mask''']
       SCREAMING_SNAKE_CASE__       :			List[str]													=1

       # first forward pass
       SCREAMING_SNAKE_CASE__       :			Any													=model(__lowercase   , attention_mask=__lowercase   , head_mask=__lowercase   , use_cache=__lowercase )

       SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__       :			Tuple													=outputs.to_tuple()

       # create hypothetical next token and extent to next_input_ids
       SCREAMING_SNAKE_CASE__       :			str													=ids_tensor((self.batch_size, 3)   , config.vocab_size )
       SCREAMING_SNAKE_CASE__       :			List[Any]													=tf.cast(ids_tensor((self.batch_size, 3)   , 2 )   , tf.inta )

       # append to next input_ids and
       SCREAMING_SNAKE_CASE__       :			Tuple													=tf.concat([input_ids, next_tokens]   , axis=-1 )
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=tf.concat([attention_mask, next_attn_mask]   , axis=-1 )

       SCREAMING_SNAKE_CASE__       :			int													=model(__lowercase   , attention_mask=__lowercase )[0]
       SCREAMING_SNAKE_CASE__       :			Any													=model(__lowercase   , attention_mask=__lowercase   , past_key_values=__lowercase )[0]

       self.parent.assertEqual(next_tokens.shape[1]   , output_from_past.shape[1] )

       # select random slice
       SCREAMING_SNAKE_CASE__       :			Optional[Any]													=int(ids_tensor((1,)   , output_from_past.shape[-1] ) )
       SCREAMING_SNAKE_CASE__       :			Any													=output_from_no_past[:, -3:, random_slice_idx]
       SCREAMING_SNAKE_CASE__       :			List[str]													=output_from_past[:, :, random_slice_idx]

       # test that outputs are equal for slice
       tf.debugging.assert_near(__lowercase   , __lowercase   , rtol=1e-3 )





def 	_a(					UpperCamelCase__			:  Any,		UpperCamelCase__			:  Union[str, Any],		UpperCamelCase__			:  Union[str, Any],		UpperCamelCase__			:  Optional[Any]=None,		UpperCamelCase__			:  Optional[Any]=None,		UpperCamelCase__			:  Union[str, Any]=None,		UpperCamelCase__			:  Any=None,		UpperCamelCase__			:  Optional[Any]=None,		):




      '''simple docstring'''






      if attention_mask is None:
            SCREAMING_SNAKE_CASE__       :			str													=tf.cast(tf.math.not_equal(UpperCamelCase__,		config.pad_token_id							),		tf.inta							)
      if decoder_attention_mask is None:
            SCREAMING_SNAKE_CASE__       :			Any													=tf.concat(
                [
                    tf.ones(decoder_input_ids[:, :1].shape,		dtype=tf.inta							),
                    tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:],		config.pad_token_id							),		tf.inta							),
                ],		axis=-1,		)
      if head_mask is None:
            SCREAMING_SNAKE_CASE__       :			int													=tf.ones((config.encoder_layers, config.encoder_attention_heads)							)
      if decoder_head_mask is None:
            SCREAMING_SNAKE_CASE__       :			List[Any]													=tf.ones((config.decoder_layers, config.decoder_attention_heads)							)
      if cross_attn_head_mask is None:
            SCREAMING_SNAKE_CASE__       :			List[str]													=tf.ones((config.decoder_layers, config.decoder_attention_heads)							)
      return {
          "input_ids": input_ids,
          "decoder_input_ids": decoder_input_ids,
          "attention_mask": attention_mask,
          "decoder_attention_mask": decoder_attention_mask,
          "head_mask": head_mask,
          "decoder_head_mask": decoder_head_mask,
          "cross_attn_head_mask": cross_attn_head_mask,
      }






@require_tf
class        __SCREAMING_SNAKE_CASE (     lowerCamelCase		,			lowerCamelCase		,			unittest.TestCase			):
 snake_case_												=							(TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
 snake_case_												=							(TFPegasusForConditionalGeneration,) if is_tf_available() else ()
 snake_case_												=							(
     {
         """conversational""": TFPegasusForConditionalGeneration,
         """feature-extraction""": TFPegasusModel,
         """summarization""": TFPegasusForConditionalGeneration,
         """text2text-generation""": TFPegasusForConditionalGeneration,
         """translation""": TFPegasusForConditionalGeneration,
     }
     if is_tf_available()
     else {}
 )
 snake_case_												=							True
 snake_case_												=							False
 snake_case_												=							False




 def        __magic_name__		( self		:							Union[str, Any] )		->  str:
       SCREAMING_SNAKE_CASE__       :			List[Any]													=TFPegasusModelTester(self )
       SCREAMING_SNAKE_CASE__       :			Dict													=ConfigTester(self   , config_class=__lowercase )




 def        __magic_name__		( self		:							int )		->  Any:
       self.config_tester.run_common_tests()




 def        __magic_name__		( self		:							Optional[Any] )		->  List[Any]:
       SCREAMING_SNAKE_CASE__       :			Tuple													=self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.check_decoder_model_past_large_inputs(*__lowercase )






@require_sentencepiece
@require_tokenizers
@require_tf
class        __SCREAMING_SNAKE_CASE (     unittest.TestCase			):
 snake_case_												=							[
     """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""",
     """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a  re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """,
 ]
 snake_case_												=							[
     """California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to"""
     """ reduce the risk of wildfires.""",
     """N-Dubz have revealed they\'re \"grateful\" to have been nominated for four Mobo Awards.""",
 ]  # differs slightly from pytorch, likely due to numerical differences in linear layers
 snake_case_												=							"""google/pegasus-xsum"""




 @cached_property
 def        __magic_name__		( self		:							Optional[int] )		->  Tuple:
       return AutoTokenizer.from_pretrained(self.model_name )




 @cached_property
 def        __magic_name__		( self		:							List[Any] )		->  Optional[Any]:
       SCREAMING_SNAKE_CASE__       :			Optional[int]													=TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )
       return model




 def        __magic_name__		( self		:							List[str]   , **__lowercase		:							Any )		->  Optional[int]:
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=self.translate_src_text(**__lowercase )
       assert self.expected_text == generated_words




 def        __magic_name__		( self		:							Optional[Any]   , **__lowercase		:							List[str] )		->  Optional[int]:
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=self.tokenizer(self.src_text   , **__lowercase   , padding=__lowercase   , return_tensors='''tf''' )
       SCREAMING_SNAKE_CASE__       :			Union[str, Any]													=self.model.generate(
           model_inputs.input_ids   , attention_mask=model_inputs.attention_mask   , num_beams=2   , use_cache=__lowercase   , )
       SCREAMING_SNAKE_CASE__       :			Any													=self.tokenizer.batch_decode(generated_ids.numpy()   , skip_special_tokens=__lowercase )
       return generated_words




 @slow
 def        __magic_name__		( self		:							Optional[Any] )		->  Optional[int]:
       self._assert_generated_batch_equal_expected()