





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 DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig
from transformers.utils import logging


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






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						int:






				"""simple docstring"""


				if "resnet-50" in model_name:
								snake_case_						:   int           =  ResNetConfig.from_pretrained('''microsoft/resnet-50'''			)
				elif "resnet-101" in model_name:
								snake_case_						:   Dict           =  ResNetConfig.from_pretrained('''microsoft/resnet-101'''			)
				else:
								raise ValueError('''Model name should include either resnet50 or resnet101'''			)

				snake_case_						:   Tuple           =  DetrConfig(use_timm_backbone=_UpperCamelCase			,    backbone_config=_UpperCamelCase			)

				# set label attributes
				snake_case_						:   Optional[Any]           =  '''panoptic''' in model_name
				if is_panoptic:
								snake_case_						:   Any           =  250
				else:
								snake_case_						:   Tuple           =  91
								snake_case_						:   List[str]           =  '''huggingface/label-files'''
								snake_case_						:   int           =  '''coco-detection-id2label.json'''
								snake_case_						:   Optional[int]           =  json.load(open(hf_hub_download(_UpperCamelCase			,    _UpperCamelCase			,    repo_type='''dataset'''			)			,    '''r'''			)			)
								snake_case_						:   Dict           =  {int(_UpperCamelCase			): v for k, v in idalabel.items()}
								snake_case_						:   Tuple           =  idalabel
								snake_case_						:   int           =  {v: k for k, v in idalabel.items()}

				return config, is_panoptic






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						List[str]:






				"""simple docstring"""


				snake_case_						:   Union[str, Any]           =  []

				# stem
				# fmt: off
				rename_keys.append(('''backbone.0.body.conv1.weight''', '''backbone.conv_encoder.model.embedder.embedder.convolution.weight''')			)
				rename_keys.append(('''backbone.0.body.bn1.weight''', '''backbone.conv_encoder.model.embedder.embedder.normalization.weight''')			)
				rename_keys.append(('''backbone.0.body.bn1.bias''', '''backbone.conv_encoder.model.embedder.embedder.normalization.bias''')			)
				rename_keys.append(('''backbone.0.body.bn1.running_mean''', '''backbone.conv_encoder.model.embedder.embedder.normalization.running_mean''')			)
				rename_keys.append(('''backbone.0.body.bn1.running_var''', '''backbone.conv_encoder.model.embedder.embedder.normalization.running_var''')			)
				# stages
				for stage_idx in range(len(config.backbone_config.depths			)			):
								for layer_idx in range(config.backbone_config.depths[stage_idx]			):
												# shortcut
												if layer_idx == 0:
																rename_keys.append(
																    (
																        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight''',
																        f'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight''',
																    )			)
																rename_keys.append(
																    (
																        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight''',
																        f'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight''',
																    )			)
																rename_keys.append(
																    (
																        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias''',
																        f'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias''',
																    )			)
																rename_keys.append(
																    (
																        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean''',
																        f'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean''',
																    )			)
																rename_keys.append(
																    (
																        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var''',
																        f'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var''',
																    )			)
												# 3 convs
												for i in range(3			):
																rename_keys.append(
																    (
																        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight''',
																        f'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight''',
																    )			)
																rename_keys.append(
																    (
																        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight''',
																        f'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight''',
																    )			)
																rename_keys.append(
																    (
																        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias''',
																        f'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias''',
																    )			)
																rename_keys.append(
																    (
																        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean''',
																        f'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean''',
																    )			)
																rename_keys.append(
																    (
																        f'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var''',
																        f'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var''',
																    )			)
    # fmt: on

				for i in range(config.encoder_layers			):
								# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
								rename_keys.append(
								    (
								        f'''transformer.encoder.layers.{i}.self_attn.out_proj.weight''',
								        f'''encoder.layers.{i}.self_attn.out_proj.weight''',
								    )			)
								rename_keys.append(
								    (f'''transformer.encoder.layers.{i}.self_attn.out_proj.bias''', f'''encoder.layers.{i}.self_attn.out_proj.bias''')			)
								rename_keys.append((f'''transformer.encoder.layers.{i}.linear1.weight''', f'''encoder.layers.{i}.fc1.weight''')			)
								rename_keys.append((f'''transformer.encoder.layers.{i}.linear1.bias''', f'''encoder.layers.{i}.fc1.bias''')			)
								rename_keys.append((f'''transformer.encoder.layers.{i}.linear2.weight''', f'''encoder.layers.{i}.fc2.weight''')			)
								rename_keys.append((f'''transformer.encoder.layers.{i}.linear2.bias''', f'''encoder.layers.{i}.fc2.bias''')			)
								rename_keys.append(
								    (f'''transformer.encoder.layers.{i}.norm1.weight''', f'''encoder.layers.{i}.self_attn_layer_norm.weight''')			)
								rename_keys.append(
								    (f'''transformer.encoder.layers.{i}.norm1.bias''', f'''encoder.layers.{i}.self_attn_layer_norm.bias''')			)
								rename_keys.append(
								    (f'''transformer.encoder.layers.{i}.norm2.weight''', f'''encoder.layers.{i}.final_layer_norm.weight''')			)
								rename_keys.append((f'''transformer.encoder.layers.{i}.norm2.bias''', f'''encoder.layers.{i}.final_layer_norm.bias''')			)
								# decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms
								rename_keys.append(
								    (
								        f'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''',
								        f'''decoder.layers.{i}.self_attn.out_proj.weight''',
								    )			)
								rename_keys.append(
								    (f'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', f'''decoder.layers.{i}.self_attn.out_proj.bias''')			)
								rename_keys.append(
								    (
								        f'''transformer.decoder.layers.{i}.multihead_attn.out_proj.weight''',
								        f'''decoder.layers.{i}.encoder_attn.out_proj.weight''',
								    )			)
								rename_keys.append(
								    (
								        f'''transformer.decoder.layers.{i}.multihead_attn.out_proj.bias''',
								        f'''decoder.layers.{i}.encoder_attn.out_proj.bias''',
								    )			)
								rename_keys.append((f'''transformer.decoder.layers.{i}.linear1.weight''', f'''decoder.layers.{i}.fc1.weight''')			)
								rename_keys.append((f'''transformer.decoder.layers.{i}.linear1.bias''', f'''decoder.layers.{i}.fc1.bias''')			)
								rename_keys.append((f'''transformer.decoder.layers.{i}.linear2.weight''', f'''decoder.layers.{i}.fc2.weight''')			)
								rename_keys.append((f'''transformer.decoder.layers.{i}.linear2.bias''', f'''decoder.layers.{i}.fc2.bias''')			)
								rename_keys.append(
								    (f'''transformer.decoder.layers.{i}.norm1.weight''', f'''decoder.layers.{i}.self_attn_layer_norm.weight''')			)
								rename_keys.append(
								    (f'''transformer.decoder.layers.{i}.norm1.bias''', f'''decoder.layers.{i}.self_attn_layer_norm.bias''')			)
								rename_keys.append(
								    (f'''transformer.decoder.layers.{i}.norm2.weight''', f'''decoder.layers.{i}.encoder_attn_layer_norm.weight''')			)
								rename_keys.append(
								    (f'''transformer.decoder.layers.{i}.norm2.bias''', f'''decoder.layers.{i}.encoder_attn_layer_norm.bias''')			)
								rename_keys.append(
								    (f'''transformer.decoder.layers.{i}.norm3.weight''', f'''decoder.layers.{i}.final_layer_norm.weight''')			)
								rename_keys.append((f'''transformer.decoder.layers.{i}.norm3.bias''', f'''decoder.layers.{i}.final_layer_norm.bias''')			)

				# convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads
				rename_keys.extend(
				    [
				        ('''input_proj.weight''', '''input_projection.weight'''),
				        ('''input_proj.bias''', '''input_projection.bias'''),
				        ('''query_embed.weight''', '''query_position_embeddings.weight'''),
				        ('''transformer.decoder.norm.weight''', '''decoder.layernorm.weight'''),
				        ('''transformer.decoder.norm.bias''', '''decoder.layernorm.bias'''),
				        ('''class_embed.weight''', '''class_labels_classifier.weight'''),
				        ('''class_embed.bias''', '''class_labels_classifier.bias'''),
				        ('''bbox_embed.layers.0.weight''', '''bbox_predictor.layers.0.weight'''),
				        ('''bbox_embed.layers.0.bias''', '''bbox_predictor.layers.0.bias'''),
				        ('''bbox_embed.layers.1.weight''', '''bbox_predictor.layers.1.weight'''),
				        ('''bbox_embed.layers.1.bias''', '''bbox_predictor.layers.1.bias'''),
				        ('''bbox_embed.layers.2.weight''', '''bbox_predictor.layers.2.weight'''),
				        ('''bbox_embed.layers.2.bias''', '''bbox_predictor.layers.2.bias'''),
				    ]			)

				return rename_keys






def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase			,    _UpperCamelCase			)		->						int:






				"""simple docstring"""


				snake_case_						:   Any           =  state_dict.pop(_UpperCamelCase			)
				snake_case_						:   Optional[int]           =  val






def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase=False			)		->						int:






				"""simple docstring"""


				snake_case_						:   Any           =  ''''''
				if is_panoptic:
								snake_case_						:   List[Any]           =  '''detr.'''

				# first: transformer encoder
				for i in range(6			):
								# read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias)
								snake_case_						:   List[Any]           =  state_dict.pop(f'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight'''			)
								snake_case_						:   Union[str, Any]           =  state_dict.pop(f'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias'''			)
								# next, add query, keys and values (in that order) to the state dict
								snake_case_						:   int           =  in_proj_weight[:256, :]
								snake_case_						:   int           =  in_proj_bias[:256]
								snake_case_						:   List[Any]           =  in_proj_weight[256:512, :]
								snake_case_						:   Tuple           =  in_proj_bias[256:512]
								snake_case_						:   Any           =  in_proj_weight[-256:, :]
								snake_case_						:   Dict           =  in_proj_bias[-256:]
				# next: transformer decoder (which is a bit more complex because it also includes cross-attention)
				for i in range(6			):
								# read in weights + bias of input projection layer of self-attention
								snake_case_						:   List[str]           =  state_dict.pop(f'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight'''			)
								snake_case_						:   List[Any]           =  state_dict.pop(f'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias'''			)
								# next, add query, keys and values (in that order) to the state dict
								snake_case_						:   Optional[int]           =  in_proj_weight[:256, :]
								snake_case_						:   Union[str, Any]           =  in_proj_bias[:256]
								snake_case_						:   Tuple           =  in_proj_weight[256:512, :]
								snake_case_						:   Any           =  in_proj_bias[256:512]
								snake_case_						:   Any           =  in_proj_weight[-256:, :]
								snake_case_						:   Optional[Any]           =  in_proj_bias[-256:]
								# read in weights + bias of input projection layer of cross-attention
								snake_case_						:   str           =  state_dict.pop(
								    f'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight'''			)
								snake_case_						:   List[Any]           =  state_dict.pop(f'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias'''			)
								# next, add query, keys and values (in that order) of cross-attention to the state dict
								snake_case_						:   List[Any]           =  in_proj_weight_cross_attn[:256, :]
								snake_case_						:   Optional[Any]           =  in_proj_bias_cross_attn[:256]
								snake_case_						:   Optional[int]           =  in_proj_weight_cross_attn[256:512, :]
								snake_case_						:   int           =  in_proj_bias_cross_attn[256:512]
								snake_case_						:   List[str]           =  in_proj_weight_cross_attn[-256:, :]
								snake_case_						:   Union[str, Any]           =  in_proj_bias_cross_attn[-256:]






def 					lowerCamelCase_						(    )		->						str:






				"""simple docstring"""


				snake_case_						:   Optional[int]           =  '''http://images.cocodataset.org/val2017/000000039769.jpg'''
				snake_case_						:   List[str]           =  Image.open(requests.get(_UpperCamelCase			,    stream=_UpperCamelCase			).raw			)

				return im






@torch.no_grad()
def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase=None			,    _UpperCamelCase=False			)		->						Optional[int]:






				"""simple docstring"""


				snake_case_      ,							snake_case_						:   Any           =  get_detr_config(_UpperCamelCase			)

				# load original model from torch hub
				snake_case_						:   Any           =  {
				    '''detr-resnet-50''': '''detr_resnet50''',
				    '''detr-resnet-101''': '''detr_resnet101''',
				}
				logger.info(f'''Converting model {model_name}...'''			)
				snake_case_						:   Optional[int]           =  torch.hub.load('''facebookresearch/detr'''			,    model_name_to_original_name[model_name]			,    pretrained=_UpperCamelCase			).eval()
				snake_case_						:   Dict           =  detr.state_dict()
				# rename keys
				for src, dest in create_rename_keys(_UpperCamelCase			):
								if is_panoptic:
												snake_case_						:   int           =  '''detr.''' + src
								rename_key(_UpperCamelCase			,    _UpperCamelCase			,    _UpperCamelCase			)
				# query, key and value matrices need special treatment
				read_in_q_k_v(_UpperCamelCase			,    is_panoptic=_UpperCamelCase			)
				# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
				snake_case_						:   str           =  '''detr.model.''' if is_panoptic else '''model.'''
				for key in state_dict.copy().keys():
								if is_panoptic:
												if (
												    key.startswith('''detr'''			)
												    and not key.startswith('''class_labels_classifier'''			)
												    and not key.startswith('''bbox_predictor'''			)
												):
																snake_case_						:   Optional[Any]           =  state_dict.pop(_UpperCamelCase			)
																snake_case_						:   Optional[int]           =  val
												elif "class_labels_classifier" in key or "bbox_predictor" in key:
																snake_case_						:   Union[str, Any]           =  state_dict.pop(_UpperCamelCase			)
																snake_case_						:   Dict           =  val
												elif key.startswith('''bbox_attention'''			) or key.startswith('''mask_head'''			):
																continue
												else:
																snake_case_						:   List[str]           =  state_dict.pop(_UpperCamelCase			)
																snake_case_						:   Optional[int]           =  val
								else:
												if not key.startswith('''class_labels_classifier'''			) and not key.startswith('''bbox_predictor'''			):
																snake_case_						:   List[Any]           =  state_dict.pop(_UpperCamelCase			)
																snake_case_						:   Optional[Any]           =  val

    # finally, create HuggingFace model and load state dict
				snake_case_						:   Dict           =  DetrForSegmentation(_UpperCamelCase			) if is_panoptic else DetrForObjectDetection(_UpperCamelCase			)
				model.load_state_dict(_UpperCamelCase			)
				model.eval()

				# verify our conversion on an image
				snake_case_						:   Dict           =  '''coco_panoptic''' if is_panoptic else '''coco_detection'''
				snake_case_						:   List[Any]           =  DetrImageProcessor(format=_UpperCamelCase			)

				snake_case_						:   List[Any]           =  processor(images=prepare_img()			,    return_tensors='''pt'''			)
				snake_case_						:   int           =  encoding['''pixel_values''']

				snake_case_						:   Optional[int]           =  detr(_UpperCamelCase			)
				snake_case_						:   Tuple           =  model(_UpperCamelCase			)

				assert torch.allclose(outputs.logits			,    original_outputs['''pred_logits''']			,    atol=1E-3			)
				assert torch.allclose(outputs.pred_boxes			,    original_outputs['''pred_boxes''']			,    atol=1E-3			)
				if is_panoptic:
								assert torch.allclose(outputs.pred_masks			,    original_outputs['''pred_masks''']			,    atol=1E-4			)
				print('''Looks ok!'''			)

				if pytorch_dump_folder_path is not None:
								# Save model and image processor
								logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...'''			)
								Path(_UpperCamelCase			).mkdir(exist_ok=_UpperCamelCase			)
								model.save_pretrained(_UpperCamelCase			)
								processor.save_pretrained(_UpperCamelCase			)

				if push_to_hub:
								# Upload model and image processor to the hub
								logger.info('''Uploading PyTorch model and image processor to the hub...'''			)
								model.push_to_hub(f'''nielsr/{model_name}'''			)
								processor.push_to_hub(f'''nielsr/{model_name}'''			)


if __name__ == "__main__":
	lowerCAmelCase_    =    argparse.ArgumentParser()

	parser.add_argument(
	    '''--model_name''',
	    default='''detr-resnet-50''',
	    type=str,
	    choices=['''detr-resnet-50''', '''detr-resnet-101'''],
	    help='''Name of the DETR model you\'d like to convert.''',
	)
	parser.add_argument(
	    '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.'''
	)
	parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Whether to push the model to the hub or not.''')
	lowerCAmelCase_    =    parser.parse_args()
	convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)







from __future__ import annotations

import unittest

import numpy as np

from transformers import OPTConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, slow

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 GPTaTokenizer, TFOPTForCausalLM, TFOPTModel






def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase			,    _UpperCamelCase=None			,    _UpperCamelCase=None			)		->						Optional[Any]:






				"""simple docstring"""


				if attention_mask is None:
								snake_case_						:   Optional[Any]           =  tf.cast(tf.math.not_equal(_UpperCamelCase			,    config.pad_token_id			)			,    tf.inta			)
				return {"input_ids": input_ids, "attention_mask": attention_mask}



@require_tf
class  __lowerCAmelCase	:
			lowerCamelCase_					:					Optional[Any]	      =				OPTConfig
			lowerCamelCase_					:					str	      =				{}
			lowerCamelCase_					:					Tuple	      =				'''gelu'''






			def __init__(self ,							__magic_name__ ,							__magic_name__=13 ,							__magic_name__=7 ,							__magic_name__=True ,							__magic_name__=False ,							__magic_name__=99 ,							__magic_name__=16 ,							__magic_name__=2 ,							__magic_name__=4 ,							__magic_name__=4 ,							__magic_name__="gelu" ,							__magic_name__=0.1 ,							__magic_name__=0.1 ,							__magic_name__=20 ,							__magic_name__=2 ,							__magic_name__=1 ,							__magic_name__=0 ,							__magic_name__=16 ,							__magic_name__=16 ,							)					->       Union[str, Any]:


							'''simple docstring'''



							snake_case_						:   List[Any]           =  parent
							snake_case_						:   int           =  batch_size
							snake_case_						:   Optional[int]           =  seq_length
							snake_case_						:   Dict           =  is_training
							snake_case_						:   str           =  use_labels
							snake_case_						:   List[str]           =  vocab_size
							snake_case_						:   Dict           =  hidden_size
							snake_case_						:   Optional[Any]           =  num_hidden_layers
							snake_case_						:   Union[str, Any]           =  num_attention_heads
							snake_case_						:   Optional[Any]           =  intermediate_size
							snake_case_						:   Optional[Any]           =  hidden_act
							snake_case_						:   Dict           =  hidden_dropout_prob
							snake_case_						:   Optional[int]           =  attention_probs_dropout_prob
							snake_case_						:   Dict           =  max_position_embeddings
							snake_case_						:   Any           =  eos_token_id
							snake_case_						:   Union[str, Any]           =  pad_token_id
							snake_case_						:   List[Any]           =  bos_token_id
							snake_case_						:   List[Any]           =  embed_dim
							snake_case_						:   Optional[int]           =  word_embed_proj_dim
							snake_case_						:   Any           =  False






			def       lowerCamelCase  (self   )					->       List[str]:


							'''simple docstring'''



							snake_case_						:   Optional[int]           =  ids_tensor([self.batch_size, self.seq_length - 1] ,							self.vocab_size   )
							snake_case_						:   Tuple           =  tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size   ) ,							1   )
							snake_case_						:   Union[str, Any]           =  tf.concat([input_ids, eos_tensor] ,							axis=1   )

							snake_case_						:   Optional[int]           =  self.config_cls(
							    vocab_size=self.vocab_size ,							hidden_size=self.hidden_size ,							num_hidden_layers=self.num_hidden_layers ,							num_attention_heads=self.num_attention_heads ,							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_id=self.eos_token_id ,							bos_token_id=self.bos_token_id ,							pad_token_id=self.pad_token_id ,							embed_dim=self.embed_dim ,							word_embed_proj_dim=self.word_embed_proj_dim ,							is_encoder_decoder=__magic_name__ ,							**self.config_updates ,							)
							snake_case_						:   Optional[Any]           =  prepare_opt_inputs_dict(__magic_name__ ,							__magic_name__   )
							return config, inputs_dict






			def       lowerCamelCase  (self ,							__magic_name__ ,							__magic_name__   )					->       Dict:


							'''simple docstring'''



							snake_case_						:   Optional[int]           =  TFOPTModel(config=__magic_name__   )
							snake_case_						:   str           =  inputs_dict['''input_ids''']

							snake_case_						:   Tuple           =  input_ids[:1, :]
							snake_case_						:   Union[str, Any]           =  inputs_dict['''attention_mask'''][:1, :]
							snake_case_						:   List[Any]           =  1

							# first forward pass
							snake_case_						:   int           =  model(__magic_name__ ,							attention_mask=__magic_name__ ,							use_cache=__magic_name__   )

							snake_case_      ,							snake_case_						:   Any           =  outputs.to_tuple()

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

							# append to next input_ids and
							snake_case_						:   Any           =  tf.concat([input_ids, next_tokens] ,							axis=-1   )
							snake_case_						:   List[str]           =  tf.concat([attention_mask, next_attn_mask] ,							axis=-1   )

							snake_case_						:   List[str]           =  model(__magic_name__ ,							attention_mask=__magic_name__   )[0]
							snake_case_						:   List[Any]           =  model(__magic_name__ ,							attention_mask=__magic_name__ ,							past_key_values=__magic_name__   )[0]

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

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

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




@require_tf
class  __lowerCAmelCase	(      _a,					_a,					unittest.TestCase					):
			lowerCamelCase_					:					Any	      =				(TFOPTModel, TFOPTForCausalLM) if is_tf_available() else ()
			lowerCamelCase_					:					List[str]	      =				(TFOPTForCausalLM,) if is_tf_available() else ()
			lowerCamelCase_					:					Optional[int]	      =				(
			    {'''feature-extraction''': TFOPTModel, '''text-generation''': TFOPTForCausalLM} if is_tf_available() else {}
			)
			lowerCamelCase_					:					List[str]	      =				False
			lowerCamelCase_					:					Tuple	      =				False
			lowerCamelCase_					:					str	      =				False
			lowerCamelCase_					:					List[str]	      =				10






			def       lowerCamelCase  (self   )					->       int:


							'''simple docstring'''



							snake_case_						:   str           =  TFOPTModelTester(self   )
							snake_case_						:   Tuple           =  ConfigTester(self ,							config_class=__magic_name__   )






			def       lowerCamelCase  (self   )					->       List[Any]:


							'''simple docstring'''



							self.config_tester.run_common_tests()






			def       lowerCamelCase  (self   )					->       int:


							'''simple docstring'''



							snake_case_						:   Any           =  self.model_tester.prepare_config_and_inputs_for_common()
							self.model_tester.check_decoder_model_past_large_inputs(*__magic_name__   )






			def       lowerCamelCase  (self   )					->       Optional[Any]:


							'''simple docstring'''



							snake_case_      ,							snake_case_						:   List[Any]           =  self.model_tester.prepare_config_and_inputs_for_common()

							def _get_word_embedding_weight(__magic_name__ ,							__magic_name__   ):
											if hasattr(__magic_name__ ,							'''weight'''   ):
															return embedding_layer.weight
											else:
															# Here we build the word embeddings weights if not exists.
															# And then we retry to get the attribute once built.
															model.build()
															if hasattr(__magic_name__ ,							'''weight'''   ):
																			return embedding_layer.weight
															else:
																			return None

							for model_class in self.all_model_classes:
											for size in [config.vocab_size - 10, config.vocab_size + 10]:
															# build the embeddings
															snake_case_						:   Optional[Any]           =  model_class(config=__magic_name__   )
															snake_case_						:   str           =  _get_word_embedding_weight(__magic_name__ ,							model.get_input_embeddings()   )
															snake_case_						:   Tuple           =  _get_word_embedding_weight(__magic_name__ ,							model.get_output_embeddings()   )

															# reshape the embeddings
															model.resize_token_embeddings(__magic_name__   )
															snake_case_						:   int           =  _get_word_embedding_weight(__magic_name__ ,							model.get_input_embeddings()   )
															snake_case_						:   Union[str, Any]           =  _get_word_embedding_weight(__magic_name__ ,							model.get_output_embeddings()   )

															# check that the resized embeddings size matches the desired size.
															snake_case_						:   List[str]           =  size if size is not None else config.vocab_size

															self.assertEqual(new_input_embeddings.shape[0] ,							__magic_name__   )

															# check that weights remain the same after resizing
															snake_case_						:   str           =  True
															for pa, pa in zip(old_input_embeddings.value() ,							new_input_embeddings.value()   ):
																			if tf.math.reduce_sum(tf.math.abs(pa - pa   )   ) > 0:
																							snake_case_						:   int           =  False
															self.assertTrue(__magic_name__   )

															if old_output_embeddings is not None and new_output_embeddings is not None:
																			self.assertEqual(new_output_embeddings.shape[0] ,							__magic_name__   )

																			snake_case_						:   Optional[int]           =  True
																			for pa, pa in zip(old_output_embeddings.value() ,							new_output_embeddings.value()   ):
																							if tf.math.reduce_sum(tf.math.abs(pa - pa   )   ) > 0:
																											snake_case_						:   Optional[Any]           =  False
																			self.assertTrue(__magic_name__   )






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						int:






				"""simple docstring"""


				return tf.constant(_UpperCamelCase			,    dtype=tf.intaa			)



@require_tf
class  __lowerCAmelCase	(      unittest.TestCase					):
			lowerCamelCase_					:					Dict	      =				99






			def       lowerCamelCase  (self   )					->       List[Any]:


							'''simple docstring'''



							snake_case_						:   List[Any]           =  tf.ones((4, 1) ,							dtype=tf.intaa   ) * 2
							snake_case_						:   Dict           =  tf.concat([ids_tensor((4, 6) ,							self.vocab_size - 3   ) + 3, eos_column_vector] ,							axis=1   )
							snake_case_						:   List[str]           =  input_ids.shape[0]
							snake_case_						:   str           =  OPTConfig(
							    vocab_size=self.vocab_size ,							hidden_size=24 ,							num_hidden_layers=2 ,							num_attention_heads=2 ,							ffn_dim=32 ,							max_position_embeddings=48 ,							eos_token_id=2 ,							pad_token_id=1 ,							bos_token_id=0 ,							)
							return config, input_ids, batch_size




@require_sentencepiece
@require_tf
class  __lowerCAmelCase	(      unittest.TestCase					):






			@slow
			def       lowerCamelCase  (self   )					->       int:


							'''simple docstring'''



							snake_case_						:   List[Any]           =  TFOPTModel.from_pretrained('''facebook/opt-350m'''   )
							snake_case_						:   Optional[Any]           =  _long_tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]   )
							snake_case_						:   Any           =  tf.not_equal(__magic_name__ ,							model.config.pad_token_id   )
							with tf.GradientTape():
											snake_case_						:   int           =  model(input_ids=__magic_name__ ,							attention_mask=__magic_name__   ).last_hidden_state
							snake_case_						:   int           =  (1, 11, 512)
							self.assertEqual(output.shape ,							__magic_name__   )
							snake_case_						:   str           =  tf.constant(
							    [[-0.2_873, -1.9_218, -0.3_033], [-1.2_710, -0.1_338, -0.1_902], [0.4_095, 0.1_214, -1.3_121]]   )
							self.assertTrue(np.allclose(output[:, :3, :3] ,							__magic_name__ ,							atol=4e-3   )   )

							snake_case_						:   Union[str, Any]           =  tf.function(__magic_name__ ,							jit_compile=__magic_name__   )
							snake_case_						:   Any           =  xla_generate(__magic_name__ ,							__magic_name__   )[0]
							self.assertTrue(np.allclose(output[:, :3, :3] ,							__magic_name__ ,							atol=4e-2   )   )




@require_tf
@slow
class  __lowerCAmelCase	(      unittest.TestCase					):






			def       lowerCamelCase  (self   )					->       Optional[Any]:


							'''simple docstring'''



							super().setUp()
							snake_case_						:   Optional[Any]           =  '''facebook/opt-350m'''






			def       lowerCamelCase  (self   )					->       Optional[int]:


							'''simple docstring'''



							snake_case_						:   int           =  TFOPTForCausalLM.from_pretrained(self.path_model   )
							snake_case_						:   Optional[Any]           =  GPTaTokenizer.from_pretrained(self.path_model   )

							snake_case_						:   List[Any]           =  [
							    '''Today is a beautiful day and I want to''',
							    '''In the city of''',
							    '''Paris is the capital of France and''',
							    '''Computers and mobile phones have taken''',
							]
							# verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
							snake_case_						:   List[str]           =  tokenizer(__magic_name__ ,							return_tensors='''tf''' ,							padding=__magic_name__ ,							add_special_tokens=__magic_name__   )
							snake_case_						:   Optional[Any]           =  tf.math.reduce_mean(model(inputs.input_ids ,							attention_mask=inputs.attention_mask   )[0] ,							axis=-1   )
							snake_case_						:   int           =  tf.constant(
							    [
							        [1.3_851, -13.8_923, -10.5_229, -10.7_533, -0.2_309, -10.2_384, -0.5_365, -9.0_947, -5.1_670],
							        [-4.7_073, -10.6_276, -3.9_415, -21.5_242, -0.2_822, -0.2_822, -0.2_822, -0.2_822, -0.2_822],
							        [0.6_247, -3.4_229, -8.9_179, -1.4_297, -14.1_650, 1.4_146, -9.0_218, -0.2_703, -0.2_703],
							        [6.4_783, -1.9_913, -10.7_926, -2.3_336, 1.5_092, -0.9_974, -6.8_213, 1.3_477, 1.3_477],
							    ]   )
							self.assertTrue(np.allclose(__magic_name__ ,							__magic_name__ ,							atol=1e-4   )   )

							snake_case_						:   str           =  tf.function(__magic_name__ ,							jit_compile=__magic_name__   )
							snake_case_						:   Optional[int]           =  tf.math.reduce_mean(xla_generate(inputs.input_ids ,							attention_mask=inputs.attention_mask   )[0] ,							axis=-1   )
							self.assertTrue(np.allclose(__magic_name__ ,							__magic_name__ ,							atol=1e-4   )   )




@require_tf
@slow
class  __lowerCAmelCase	(      unittest.TestCase					):






			@property
			def       lowerCamelCase  (self   )					->       Tuple:


							'''simple docstring'''



							return [
							    "Today is a beautiful day and I want",
							    "In the city of",
							    "Paris is the capital of France and",
							    "Computers and mobile phones have taken",
							]






			def       lowerCamelCase  (self   )					->       Dict:


							'''simple docstring'''



							snake_case_						:   Any           =  '''facebook/opt-125m'''

							snake_case_						:   List[str]           =  [
							    '''Today is a beautiful day and I want to''',
							    '''In the city of New York, the city''',
							    '''Paris is the capital of France and the capital''',
							    '''Computers and mobile phones have taken over the''',
							]

							snake_case_						:   Optional[Any]           =  []
							snake_case_						:   Any           =  GPTaTokenizer.from_pretrained(__magic_name__   )
							snake_case_						:   Optional[Any]           =  TFOPTForCausalLM.from_pretrained(__magic_name__   )

							for prompt in self.prompts:
											snake_case_						:   List[Any]           =  tokenizer(__magic_name__ ,							return_tensors='''tf'''   ).input_ids

											snake_case_						:   Any           =  model.generate(__magic_name__ ,							max_length=10   )

											snake_case_						:   Union[str, Any]           =  tokenizer.batch_decode(__magic_name__ ,							skip_special_tokens=__magic_name__   )
											predicted_outputs += generated_string

							self.assertListEqual(__magic_name__ ,							__magic_name__   )






			def       lowerCamelCase  (self   )					->       int:


							'''simple docstring'''



							snake_case_						:   Dict           =  '''facebook/opt-350m'''

							snake_case_						:   int           =  GPTaTokenizer.from_pretrained(__magic_name__   )
							snake_case_						:   Optional[Any]           =  TFOPTForCausalLM.from_pretrained(__magic_name__   )

							snake_case_						:   List[str]           =  '''left'''

							# use different length sentences to test batching
							snake_case_						:   Optional[Any]           =  [
							    '''Hello, my dog is a little''',
							    '''Today, I''',
							]

							snake_case_						:   Tuple           =  tokenizer(__magic_name__ ,							return_tensors='''tf''' ,							padding=__magic_name__   )
							snake_case_						:   int           =  inputs['''input_ids''']

							snake_case_						:   Optional[int]           =  model.generate(input_ids=__magic_name__ ,							attention_mask=inputs['''attention_mask''']   )

							snake_case_						:   Any           =  tokenizer(sentences[0] ,							return_tensors='''tf'''   ).input_ids
							snake_case_						:   int           =  model.generate(input_ids=__magic_name__   )

							snake_case_						:   List[str]           =  inputs_non_padded.shape[-1] - tf.math.reduce_sum(
							    tf.cast(inputs['''attention_mask'''][-1] ,							tf.intaa   )   )
							snake_case_						:   Optional[Any]           =  tokenizer(sentences[1] ,							return_tensors='''tf'''   ).input_ids
							snake_case_						:   int           =  model.generate(input_ids=__magic_name__ ,							max_length=model.config.max_length - num_paddings   )

							snake_case_						:   Union[str, Any]           =  tokenizer.batch_decode(__magic_name__ ,							skip_special_tokens=__magic_name__   )
							snake_case_						:   List[Any]           =  tokenizer.decode(output_non_padded[0] ,							skip_special_tokens=__magic_name__   )
							snake_case_						:   str           =  tokenizer.decode(output_padded[0] ,							skip_special_tokens=__magic_name__   )

							snake_case_						:   Any           =  [
							    '''Hello, my dog is a little bit of a dork.\nI\'m a little bit''',
							    '''Today, I was in the middle of a conversation with a friend about the''',
							]
							self.assertListEqual(__magic_name__ ,							__magic_name__   )
							self.assertListEqual(__magic_name__ ,							[non_padded_sentence, padded_sentence]   )






			def       lowerCamelCase  (self   )					->       List[Any]:


							'''simple docstring'''



							snake_case_						:   Tuple           =  '''facebook/opt-350m'''

							snake_case_						:   Optional[Any]           =  [
							    '''Today is a beautiful day and I want to''',
							    '''In the city of San Francisco, the city''',
							    '''Paris is the capital of France and the capital''',
							    '''Computers and mobile phones have taken over the''',
							]

							snake_case_						:   Dict           =  []
							snake_case_						:   Tuple           =  GPTaTokenizer.from_pretrained(__magic_name__   )
							snake_case_						:   Tuple           =  TFOPTForCausalLM.from_pretrained(__magic_name__   )

							for prompt in self.prompts:
											snake_case_						:   Tuple           =  tokenizer(__magic_name__ ,							return_tensors='''tf'''   ).input_ids

											snake_case_						:   int           =  model.generate(__magic_name__ ,							max_length=10   )

											snake_case_						:   Optional[int]           =  tokenizer.batch_decode(__magic_name__ ,							skip_special_tokens=__magic_name__   )
											predicted_outputs += generated_string

							self.assertListEqual(__magic_name__ ,							__magic_name__   )
