






"""simple docstring"""


import argparse
import collections

import jax
import jax.numpy as jnp
import torch
import torch.nn as nn
from clip.model import CLIP
from flax.training import checkpoints
from huggingface_hub import Repository

from transformers import (
    CLIPTokenizer,
    OwlViTConfig,
    OwlViTForObjectDetection,
    OwlViTImageProcessor,
    OwlViTModel,
    OwlViTProcessor,
)


__SCREAMING_SNAKE_CASE      =      {
    'vit_b32': {
        'embed_dim': 5_12,
        'image_resolution': 7_68,
        'context_length': 16,
        'vocab_size': 4_94_08,
        'vision_layers': 12,
        'vision_width': 7_68,
        'vision_patch_size': 32,
        'transformer_width': 5_12,
        'transformer_heads': 8,
        'transformer_layers': 12,
    },
    'vit_b16': {
        'embed_dim': 5_12,
        'image_resolution': 7_68,
        'context_length': 16,
        'vocab_size': 4_94_08,
        'vision_layers': 12,
        'vision_width': 7_68,
        'vision_patch_size': 16,
        'transformer_width': 5_12,
        'transformer_heads': 8,
        'transformer_layers': 12,
    },
    'vit_l14': {
        'embed_dim': 7_68,
        'image_resolution': 8_40,
        'context_length': 16,
        'vocab_size': 4_94_08,
        'vision_layers': 24,
        'vision_width': 10_24,
        'vision_patch_size': 14,
        'transformer_width': 7_68,
        'transformer_heads': 12,
        'transformer_layers': 12,
    },
}


def 					UpperCAmelCase			(				a__    ,			a__=""    ,			a__="/"   ):





						'''simple docstring'''






						lowerCAmelCase      :Tuple				  = []

						for k, v in params.items():
												lowerCAmelCase      :Tuple				  = parent_key + sep + k if parent_key else k

												if isinstance(a__    ,			collections.MutableMapping   ):
																		items.extend(flatten_nested_dict(a__    ,			a__    ,			sep=a__   ).items()   )
												else:
																		items.append((new_key, v)   )
						return dict(a__   )


def 					UpperCAmelCase			(				a__   ):





						'''simple docstring'''






						return jax.tree_util.tree_map(lambda a__   : x.astype(jnp.floataa   ) if x.dtype == jnp.bfloataa else x    ,			a__   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase  ,   lowerCAmelCase  ,   lowerCAmelCase      :int				  = pt_attn_layer.in_proj_weight.chunk(3    ,			dim=0   )
						lowerCAmelCase  ,   lowerCAmelCase  ,   lowerCAmelCase      :Union[str, Any]				  = pt_attn_layer.in_proj_bias.chunk(3    ,			dim=0   )

						lowerCAmelCase      :int				  = pt_attn_layer.out_proj.weight
						lowerCAmelCase      :List[str]				  = pt_attn_layer.out_proj.bias

						lowerCAmelCase      :str				  = q_proj
						lowerCAmelCase      :Any				  = q_proj_bias

						lowerCAmelCase      :Tuple				  = k_proj
						lowerCAmelCase      :Any				  = k_proj_bias

						lowerCAmelCase      :Optional[int]				  = v_proj
						lowerCAmelCase      :Any				  = v_proj_bias

						lowerCAmelCase      :Optional[Any]				  = out_proj_weights
						lowerCAmelCase      :Optional[Any]				  = out_proj_bias


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						copy_linear(hf_mlp.fca    ,			pt_mlp.c_fc   )
						copy_linear(hf_mlp.fca    ,			pt_mlp.c_proj   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :List[Any]				  = pt_linear.weight
						lowerCAmelCase      :Any				  = pt_linear.bias


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						copy_linear(hf_layer.layer_norma    ,			pt_layer.ln_a   )
						copy_linear(hf_layer.layer_norma    ,			pt_layer.ln_a   )

						# copy MLP
						copy_mlp(hf_layer.mlp    ,			pt_layer.mlp   )

						# copy attn
						copy_attn_layer(hf_layer.self_attn    ,			pt_layer.attn   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						for hf_layer, pt_layer in zip(a__    ,			a__   ):
												copy_layer(a__    ,			a__   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :Any				  = pt_model.token_embedding.weight
						lowerCAmelCase      :Any				  = pt_model.positional_embedding

						# copy layer norm
						copy_linear(hf_encoder.final_layer_norm    ,			pt_model.ln_final   )

						# copy hidden layers
						copy_layers(hf_encoder.encoder.layers    ,			pt_model.transformer.resblocks   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :Tuple				  = pt_model.text_projection.data.T

						# copy text encoder
						copy_encoder(hf_model.text_model    ,			a__   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :Optional[Any]				  = pt_model.visual.proj.data.T

						# copy layer norms
						copy_linear(hf_model.vision_model.pre_layernorm    ,			pt_model.visual.ln_pre   )
						copy_linear(hf_model.vision_model.post_layernorm    ,			pt_model.visual.ln_post   )

						# copy embeds
						lowerCAmelCase      :Optional[int]				  = pt_model.visual.conva.weight.data
						lowerCAmelCase      :Tuple				  = pt_model.visual.class_embedding
						lowerCAmelCase      :Union[str, Any]				  = pt_model.visual.positional_embedding.data

						# copy encoder
						copy_layers(hf_model.vision_model.encoder.layers    ,			pt_model.visual.transformer.resblocks   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :int				  = flatten_nested_dict(flax_params['backbone']['merged_class_token']   )

						lowerCAmelCase      :Tuple				  = torch.from_numpy(flax_class_token_params['scale']   )
						lowerCAmelCase      :Dict				  = torch.from_numpy(flax_class_token_params['bias']   )
						lowerCAmelCase      :Dict				  = nn.Parameter(a__   )
						lowerCAmelCase      :Tuple				  = nn.Parameter(a__   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :List[str]				  = hf_model.state_dict()
						lowerCAmelCase      :Union[str, Any]				  = {}

						# Rename class prediction head flax params to pytorch HF
						lowerCAmelCase      :Any				  = flatten_nested_dict(flax_params['class_head']   )

						for flax_key, v in flax_class_params.items():
												lowerCAmelCase      :Optional[Any]				  = flax_key.replace('/'    ,			'.'   )
												lowerCAmelCase      :Any				  = torch_key.replace('.kernel'    ,			'.weight'   )
												lowerCAmelCase      :List[Any]				  = torch_key.replace('Dense_0'    ,			'dense0'   )
												lowerCAmelCase      :Optional[Any]				  = 'class_head.' + torch_key

												if "weight" in torch_key and v.ndim == 2:
																		lowerCAmelCase      :Tuple				  = v.T

												lowerCAmelCase      :int				  = nn.Parameter(torch.from_numpy(a__   )   )

						# Rename box prediction box flax params to pytorch HF
						lowerCAmelCase      :str				  = flatten_nested_dict(flax_params['obj_box_head']   )

						for flax_key, v in flax_box_params.items():
												lowerCAmelCase      :List[str]				  = flax_key.replace('/'    ,			'.'   )
												lowerCAmelCase      :Optional[int]				  = torch_key.replace('.kernel'    ,			'.weight'   )
												lowerCAmelCase      :List[str]				  = torch_key.replace('_'    ,			''   ).lower()
												lowerCAmelCase      :Dict				  = 'box_head.' + torch_key

												if "weight" in torch_key and v.ndim == 2:
																		lowerCAmelCase      :Tuple				  = v.T

												lowerCAmelCase      :List[Any]				  = nn.Parameter(torch.from_numpy(a__   )   )

						# Copy flax params to PyTorch params
						for name, param in new_params.items():
												if name in pt_params.keys():
																		pt_params[name].copy_(a__   )


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						for k, v in flax_attn_params.items():
												if k.startswith('transformer'   ):
																		lowerCAmelCase      :Union[str, Any]				  = k.replace('transformer.resblocks'    ,			'text_model.encoder.layers'   )
												else:
																		lowerCAmelCase      :Any				  = k.replace('visual.transformer.resblocks'    ,			'vision_model.encoder.layers'   )

												lowerCAmelCase      :str				  = torch_key.replace('attn'    ,			'self_attn'   )
												lowerCAmelCase      :Optional[Any]				  = torch_key.replace('key'    ,			'k_proj'   )
												lowerCAmelCase      :int				  = torch_key.replace('value'    ,			'v_proj'   )
												lowerCAmelCase      :List[str]				  = torch_key.replace('query'    ,			'q_proj'   )
												lowerCAmelCase      :List[str]				  = torch_key.replace('out'    ,			'out_proj'   )

												if "bias" in torch_key and v.ndim == 2:
																		lowerCAmelCase      :List[Any]				  = v.shape[0] * v.shape[1]
																		lowerCAmelCase      :str				  = v.reshape(a__   )

												if "weight" in torch_key and "out" in torch_key:
																		lowerCAmelCase      :Tuple				  = (v.shape[0] * v.shape[1], v.shape[2])
																		lowerCAmelCase      :int				  = v.reshape(a__   ).T

												if "weight" in torch_key and "out" not in torch_key:
																		lowerCAmelCase      :Optional[Any]				  = (v.shape[0], v.shape[1] * v.shape[2])
																		lowerCAmelCase      :Optional[Any]				  = v.reshape(a__   ).T

												# Copy flax CLIP attn params to HF PyTorch params
												lowerCAmelCase      :Any				  = torch.from_numpy(a__   )
												hf_backbone.state_dict()[torch_key].copy_(a__   )


def 					UpperCAmelCase			(				a__   ):





						'''simple docstring'''






						lowerCAmelCase      :List[Any]				  = {}
						lowerCAmelCase      :Union[str, Any]				  = []

						for k, v in params.items():
												if "attn." in k:
																		lowerCAmelCase      :Optional[Any]				  = k[: k.rindex('attn.'   ) + 5]
																		if base in processed_attn_layers:
																								continue

																		processed_attn_layers.append(a__   )
																		lowerCAmelCase      :Tuple				  = params[base + 'out.weight'].shape[-1]
																		lowerCAmelCase      :Tuple				  = params[base + 'out.weight'].reshape(a__    ,			a__   ).T
																		lowerCAmelCase      :Optional[Any]				  = params[base + 'out.bias']
												else:
																		lowerCAmelCase      :List[Any]				  = v
						return new_params


def 					UpperCAmelCase			(				a__    ,			a__   ):





						'''simple docstring'''






						lowerCAmelCase      :str				  = CLIP(**a__   )
						torch_model.eval()
						lowerCAmelCase      :str				  = torch_model.state_dict()

						lowerCAmelCase      :Optional[Any]				  = flatten_nested_dict(flax_params['backbone']['clip']   )
						lowerCAmelCase      :Any				  = {}

						for flax_key, v in flax_clip_params.items():
												lowerCAmelCase      :int				  = flax_key.replace('/'    ,			'.'   )
												lowerCAmelCase      :Any				  = torch_key.replace('text.token_embedding.embedding'    ,			'token_embedding.kernel'   )

												if (
												    torch_key.startswith('text.transformer'   )
												    or torch_key.startswith('text.text_projection'   )
												    or torch_key.startswith('text.ln_final'   )
												    or torch_key.startswith('text.positional_embedding'   )
												):
																		lowerCAmelCase      :Optional[Any]				  = torch_key[5:]

												lowerCAmelCase      :List[Any]				  = torch_key.replace('text_projection.kernel'    ,			'text_projection'   )
												lowerCAmelCase      :Union[str, Any]				  = torch_key.replace('visual.proj.kernel'    ,			'visual.proj'   )
												lowerCAmelCase      :Tuple				  = torch_key.replace('.scale'    ,			'.weight'   )
												lowerCAmelCase      :List[Any]				  = torch_key.replace('.kernel'    ,			'.weight'   )

												if "conv" in torch_key or "downsample.0.weight" in torch_key:
																		lowerCAmelCase      :Union[str, Any]				  = v.transpose(3    ,			2    ,			0    ,			1   )

												elif "weight" in torch_key and v.ndim == 2 and "embedding" not in torch_key:
																		# Fully connected layers are transposed, embeddings are not
																		lowerCAmelCase      :int				  = v.T

												lowerCAmelCase      :Optional[int]				  = v

						lowerCAmelCase      :Tuple				  = _convert_attn_layers(a__   )
						new_torch_params.update(a__   )
						lowerCAmelCase      :Union[str, Any]				  = {}

						# Copy flax CLIP backbone params to PyTorch params
						for name, param in new_torch_params.items():
												if name in torch_clip_params.keys():
																		lowerCAmelCase      :Tuple				  = torch.from_numpy(new_torch_params[name]   )
																		torch_clip_params[name].copy_(a__   )
												else:
																		lowerCAmelCase      :List[Any]				  = param

						return torch_clip_params, torch_model, attn_params


@torch.no_grad()
def 					UpperCAmelCase			(				a__    ,			a__    ,			a__    ,			a__    ,			a__=None   ):





						'''simple docstring'''






						lowerCAmelCase      :int				  = Repository(a__    ,			clone_from=F"""google/{pytorch_dump_folder_path}"""   )
						repo.git_pull()

						if config_path is not None:
												lowerCAmelCase      :Optional[int]				  = OwlViTConfig.from_pretrained(a__   )
						else:
												lowerCAmelCase      :Tuple				  = OwlViTConfig()

						lowerCAmelCase      :Any				  = OwlViTModel(a__   ).eval()
						lowerCAmelCase      :Dict				  = OwlViTForObjectDetection(a__   ).eval()

						copy_text_model_and_projection(a__    ,			a__   )
						copy_vision_model_and_projection(a__    ,			a__   )
						lowerCAmelCase      :Any				  = pt_backbone.logit_scale
						copy_flax_attn_params(a__    ,			a__   )

						lowerCAmelCase      :Optional[Any]				  = hf_backbone
						copy_class_merge_token(a__    ,			a__   )
						copy_class_box_heads(a__    ,			a__   )

						# Save HF model
						hf_model.save_pretrained(repo.local_dir   )

						# Initialize image processor
						lowerCAmelCase      :Union[str, Any]				  = OwlViTImageProcessor(
						    size=config.vision_config.image_size    ,			crop_size=config.vision_config.image_size   )
						# Initialize tokenizer
						lowerCAmelCase      :Optional[Any]				  = CLIPTokenizer.from_pretrained('openai/clip-vit-base-patch32'    ,			pad_token='!'    ,			model_max_length=16   )

						# Initialize processor
						lowerCAmelCase      :Dict				  = OwlViTProcessor(image_processor=a__    ,			tokenizer=a__   )
						image_processor.save_pretrained(repo.local_dir   )
						processor.save_pretrained(repo.local_dir   )

						repo.git_add()
						repo.git_commit('Upload model and processor'   )
						repo.git_push()


if __name__ == "__main__":
		__SCREAMING_SNAKE_CASE      =      argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    '--owlvit_version',
		    default=None,
		    type=str,
		    required=True,
		    help='OWL-ViT model name [clip_b16, clip_b32, clip_l14].',
		)
		parser.add_argument(
		    '--owlvit_checkpoint', default=None, type=str, required=True, help='Path to flax model checkpoint.'
		)
		parser.add_argument('--hf_config', default=None, type=str, required=True, help='Path to HF model config.')
		parser.add_argument(
		    '--pytorch_dump_folder_path', default='hf_model', type=str, help='Path to the output PyTorch model.'
		)
		__SCREAMING_SNAKE_CASE      =      parser.parse_args()

		# Initialize PyToch clip model
		__SCREAMING_SNAKE_CASE      =      args.owlvit_version
		if model_name == "clip_b16":
				__SCREAMING_SNAKE_CASE      =      CONFIGS['vit_b16']
		elif model_name == "clip_b32":
				__SCREAMING_SNAKE_CASE      =      CONFIGS['vit_b32']
		elif model_name == "clip_l14":
				__SCREAMING_SNAKE_CASE      =      CONFIGS['vit_l14']

		# Load from checkpoint and convert params to float-32
		__SCREAMING_SNAKE_CASE      =      checkpoints.restore_checkpoint(args.owlvit_checkpoint, target=None)['optimizer']['target']
		__SCREAMING_SNAKE_CASE      =      jax.tree_util.tree_map(lambda x: x.astype(jnp.floataa) if x.dtype == jnp.bfloataa else x, variables)
		del variables

		# Convert CLIP backbone
		__SCREAMING_SNAKE_CASE,	__SCREAMING_SNAKE_CASE,	__SCREAMING_SNAKE_CASE      =      convert_clip_backbone(flax_params, torch_config)

		convert_owlvit_checkpoint(clip_pt, flax_params, attn_params, args.pytorch_dump_folder_path, args.hf_config)







"""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 	__UpperCamelCase    (    unittest.TestCase	):
					@slow
					def 					UpperCAmelCase__   (       self       :  Tuple      )  ->					Union[str, Any]:
											lowerCAmelCase      :Any				  = XLMProphetNetForConditionalGeneration.from_pretrained('microsoft/xprophetnet-large-wiki100-cased'      )
											model.to(UpperCAmelCase      )

											# encoder-decoder outputs
											lowerCAmelCase      :Any				  = torch.tensor([[17, 9_6208, 10_3471, 2]]      ).to(UpperCAmelCase      )
											lowerCAmelCase      :Optional[int]				  = torch.tensor(
											    [[2, 250, 9953, 34, 6_9489, 1620, 32, 11_8424, 624, 210, 105, 2913, 1032, 351]]      ).to(UpperCAmelCase      )
											lowerCAmelCase      :Tuple				  = model(
											    input_ids=UpperCAmelCase    ,   attention_mask=UpperCAmelCase    ,   encoder_outputs=UpperCAmelCase    ,   decoder_input_ids=UpperCAmelCase      )
											lowerCAmelCase      :Tuple				  = output[0]
											lowerCAmelCase      :Any				  = torch.Size((1, 14, 25_0012)      )
											self.assertEqual(output_predited_logis.shape    ,   UpperCAmelCase      )
											lowerCAmelCase      :Optional[int]				  = torch.tensor(
											    [[[-6.3_9_8_6, -8.2_3_9_1, 1_2.5_1_8_9], [-6.3_2_8_9, -8.0_8_6_4, 1_2.6_2_1_1], [-6.2_4_1_8, -8.0_4_4_5, 1_2.7_9_6_8]]]      ).to(UpperCAmelCase      )
											self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]    ,   UpperCAmelCase    ,   atol=1e-4      )      )

											# encoder outputs
											lowerCAmelCase      :int				  = model.prophetnet.encoder(UpperCAmelCase      )[0]
											lowerCAmelCase      :int				  = torch.tensor(
											    [[[-1.4_2_6_0, -0.7_6_2_8, 0.8_4_5_3], [-1.4_7_1_9, -0.1_3_9_1, 0.7_8_0_7], [-1.7_6_7_8, 0.0_1_1_4, 0.4_6_4_6]]]      ).to(UpperCAmelCase      )
											lowerCAmelCase      :Optional[Any]				  = torch.Size((1, 4, 1024)      )
											self.assertEqual(encoder_outputs.shape    ,   UpperCAmelCase      )
											self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3]    ,   UpperCAmelCase    ,   atol=1e-4      )      )

											# decoder outputs
											lowerCAmelCase      :Tuple				  = model.prophetnet.decoder(
											    UpperCAmelCase    ,   encoder_hidden_states=UpperCAmelCase    ,   )
											lowerCAmelCase      :Optional[Any]				  = decoder_outputs[1].view(1    ,   model.config.ngram    ,   14    ,   -1      )
											lowerCAmelCase      :Any				  = model.lm_head(UpperCAmelCase      )
											lowerCAmelCase      :Optional[int]				  = predicting_streams_logits[:, 0]
											self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3]    ,   UpperCAmelCase    ,   atol=1e-4      )      )
					@slow
					def 					UpperCAmelCase__   (       self       :  List[Any]      )  ->					Optional[Any]:
											lowerCAmelCase      :Union[str, Any]				  = XLMProphetNetForConditionalGeneration.from_pretrained(
											    'microsoft/xprophetnet-large-wiki100-cased-xglue-ntg'      )
											model.to(UpperCAmelCase      )

											lowerCAmelCase      :Tuple				  = torch.tensor([[17, 9_6208, 10_3471, 2]]      ).to(UpperCAmelCase      )
											lowerCAmelCase      :Any				  = torch.tensor(
											    [[2, 250, 9953, 34, 6_9489, 1620, 32, 11_8424, 624, 210, 105, 2913, 1032, 351]]      ).to(UpperCAmelCase      )
											lowerCAmelCase      :Tuple				  = model(
											    input_ids=UpperCAmelCase    ,   attention_mask=UpperCAmelCase    ,   encoder_outputs=UpperCAmelCase    ,   decoder_input_ids=UpperCAmelCase      )
											lowerCAmelCase      :Dict				  = output[0]
											lowerCAmelCase      :List[str]				  = torch.Size((1, 14, 25_0012)      )
											self.assertEqual(output_predited_logis.shape    ,   UpperCAmelCase      )
											# compare the actual values for a slice.
											lowerCAmelCase      :List[Any]				  = torch.tensor(
											    [[[-9.2_2_5_3, -9.7_1_7_3, -6.3_5_2_9], [-7.6_7_0_1, -9.0_1_4_5, -1.9_3_8_2], [-8.0_1_9_5, -7.0_0_0_4, -0.1_5_2_3]]]      ).to(UpperCAmelCase      )

											self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]    ,   UpperCAmelCase    ,   atol=1e-4      )      )
					@slow
					def 					UpperCAmelCase__   (       self       :  Optional[Any]      )  ->					Optional[int]:
											lowerCAmelCase      :str				  = XLMProphetNetForConditionalGeneration.from_pretrained(
											    'microsoft/xprophetnet-large-wiki100-cased-xglue-ntg'      )
											model.to(UpperCAmelCase      )
											lowerCAmelCase      :Any				  = 512

											lowerCAmelCase      :Union[str, Any]				  = XLMProphetNetTokenizer.from_pretrained('microsoft/xprophetnet-large-wiki100-cased-xglue-ntg'      )

											lowerCAmelCase      :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.'
											)
											lowerCAmelCase      :Union[str, Any]				  = (
											    'орпорация Microsoft намерена официально прекратить бесплатную поддержку операционной системы Windows 7'
											    ' после 14 января 2020 года, сообщается на официальном портале организации . С указанного дня пользователи'
											    ' этой системы не смогут получать обновления безопасности, из-за чего их компьютеры могут стать уязвимыми'
											    ' к кибератакам.'
											)
											lowerCAmelCase      :Optional[Any]				  = (
											    '根据该组织的官方门户网站，微软公司打算在2020年1月14日之后正式终止对Windows 7操作系统的免费支持。从那时起，该系统的用户将无法接收安全更新，这可能会使他们的计算机容易受到网络攻击。'
											)

											lowerCAmelCase      :List[Any]				  = tokenizer(
											    [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE]    ,   padding=UpperCAmelCase    ,   max_length=255    ,   return_tensors='pt'      ).input_ids
											lowerCAmelCase      :List[str]				  = input_ids.to(UpperCAmelCase      )

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

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