





from typing import Optional, Union

import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig


lowerCAmelCase_    =    logging.get_logger(__name__)


# General docstring
lowerCAmelCase_    =    '''MobileNetV1Config'''

# Base docstring
lowerCAmelCase_    =    '''google/mobilenet_v1_1.0_224'''
lowerCAmelCase_    =    [1, 1_0_2_4, 7, 7]

# Image classification docstring
lowerCAmelCase_    =    '''google/mobilenet_v1_1.0_224'''
lowerCAmelCase_    =    '''tabby, tabby cat'''


lowerCAmelCase_    =    [
    '''google/mobilenet_v1_1.0_224''',
    '''google/mobilenet_v1_0.75_192''',
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]






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






				"""simple docstring"""


				snake_case_						:   Dict           =  {}

				if isinstance(_UpperCamelCase			,    _UpperCamelCase			):
								snake_case_						:   List[str]           =  model.mobilenet_va
				else:
								snake_case_						:   List[str]           =  model

				snake_case_						:   Optional[int]           =  '''MobilenetV1/Conv2d_0/'''
				snake_case_						:   Dict           =  backbone.conv_stem.convolution.weight
				snake_case_						:   List[str]           =  backbone.conv_stem.normalization.bias
				snake_case_						:   List[Any]           =  backbone.conv_stem.normalization.weight
				snake_case_						:   List[str]           =  backbone.conv_stem.normalization.running_mean
				snake_case_						:   List[str]           =  backbone.conv_stem.normalization.running_var

				for i in range(13			):
								snake_case_						:   List[str]           =  i + 1
								snake_case_						:   Any           =  i * 2

								snake_case_						:   int           =  backbone.layer[pt_index]
								snake_case_						:   Union[str, Any]           =  f'''MobilenetV1/Conv2d_{tf_index}_depthwise/'''
								snake_case_						:   Union[str, Any]           =  pointer.convolution.weight
								snake_case_						:   List[str]           =  pointer.normalization.bias
								snake_case_						:   List[Any]           =  pointer.normalization.weight
								snake_case_						:   Dict           =  pointer.normalization.running_mean
								snake_case_						:   Optional[Any]           =  pointer.normalization.running_var

								snake_case_						:   Dict           =  backbone.layer[pt_index + 1]
								snake_case_						:   Optional[Any]           =  f'''MobilenetV1/Conv2d_{tf_index}_pointwise/'''
								snake_case_						:   Optional[Any]           =  pointer.convolution.weight
								snake_case_						:   str           =  pointer.normalization.bias
								snake_case_						:   Union[str, Any]           =  pointer.normalization.weight
								snake_case_						:   List[str]           =  pointer.normalization.running_mean
								snake_case_						:   Tuple           =  pointer.normalization.running_var

				if isinstance(_UpperCamelCase			,    _UpperCamelCase			):
								snake_case_						:   Dict           =  '''MobilenetV1/Logits/Conv2d_1c_1x1/'''
								snake_case_						:   List[str]           =  model.classifier.weight
								snake_case_						:   Any           =  model.classifier.bias

				return tf_to_pt_map






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






				"""simple docstring"""


				try:
								import numpy as np
								import tensorflow as tf
				except ImportError:
								logger.error(
								    '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see '''
								    '''https://www.tensorflow.org/install/ for installation instructions.'''			)
								raise

				# Load weights from TF model
				snake_case_						:   str           =  tf.train.list_variables(_UpperCamelCase			)
				snake_case_						:   Union[str, Any]           =  {}
				for name, shape in init_vars:
								logger.info(f'''Loading TF weight {name} with shape {shape}'''			)
								snake_case_						:   Union[str, Any]           =  tf.train.load_variable(_UpperCamelCase			,    _UpperCamelCase			)
								snake_case_						:   Any           =  array

				# Build TF to PyTorch weights loading map
				snake_case_						:   str           =  _build_tf_to_pytorch_map(_UpperCamelCase			,    _UpperCamelCase			,    _UpperCamelCase			)

				for name, pointer in tf_to_pt_map.items():
								logger.info(f'''Importing {name}'''			)
								if name not in tf_weights:
												logger.info(f'''{name} not in tf pre-trained weights, skipping'''			)
												continue

								snake_case_						:   List[Any]           =  tf_weights[name]

								if "depthwise_weights" in name:
												logger.info('''Transposing depthwise'''			)
												snake_case_						:   List[str]           =  np.transpose(_UpperCamelCase			,    (2, 3, 0, 1)			)
								elif "weights" in name:
												logger.info('''Transposing'''			)
												if len(pointer.shape			) == 2:  # copying into linear layer
																snake_case_						:   List[str]           =  array.squeeze().transpose()
												else:
																snake_case_						:   Tuple           =  np.transpose(_UpperCamelCase			,    (3, 2, 0, 1)			)

								if pointer.shape != array.shape:
												raise ValueError(f'''Pointer shape {pointer.shape} and array shape {array.shape} mismatched'''			)

								logger.info(f'''Initialize PyTorch weight {name} {array.shape}'''			)
								snake_case_						:   str           =  torch.from_numpy(_UpperCamelCase			)

								tf_weights.pop(_UpperCamelCase			,    _UpperCamelCase			)
								tf_weights.pop(name + '''/RMSProp'''			,    _UpperCamelCase			)
								tf_weights.pop(name + '''/RMSProp_1'''			,    _UpperCamelCase			)
								tf_weights.pop(name + '''/ExponentialMovingAverage'''			,    _UpperCamelCase			)

				logger.info(f'''Weights not copied to PyTorch model: {", ".join(tf_weights.keys()			)}'''			)
				return model






def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase			)		->						torch.Tensor:






				"""simple docstring"""


				snake_case_      ,							snake_case_						:   Tuple           =  features.shape[-2:]
				snake_case_      ,							snake_case_						:   Optional[Any]           =  conv_layer.stride
				snake_case_      ,							snake_case_						:   Union[str, Any]           =  conv_layer.kernel_size

				if in_height % stride_height == 0:
								snake_case_						:   Optional[Any]           =  max(kernel_height - stride_height			,    0			)
				else:
								snake_case_						:   Optional[int]           =  max(kernel_height - (in_height % stride_height)			,    0			)

				if in_width % stride_width == 0:
								snake_case_						:   int           =  max(kernel_width - stride_width			,    0			)
				else:
								snake_case_						:   Optional[Any]           =  max(kernel_width - (in_width % stride_width)			,    0			)

				snake_case_						:   Any           =  pad_along_width // 2
				snake_case_						:   Optional[Any]           =  pad_along_width - pad_left
				snake_case_						:   Dict           =  pad_along_height // 2
				snake_case_						:   Dict           =  pad_along_height - pad_top

				snake_case_						:   List[Any]           =  (pad_left, pad_right, pad_top, pad_bottom)
				return nn.functional.pad(_UpperCamelCase			,    _UpperCamelCase			,    '''constant'''			,    0.0			)



class  __lowerCAmelCase	(      nn.Module					):






			def __init__(self ,							__magic_name__ ,							__magic_name__ ,							__magic_name__ ,							__magic_name__ ,							__magic_name__ = 1 ,							__magic_name__ = 1 ,							__magic_name__ = False ,							__magic_name__ = True ,							__magic_name__ = True ,							)					->       None:


							'''simple docstring'''



							super().__init__()
							snake_case_						:   Union[str, Any]           =  config

							if in_channels % groups != 0:
											raise ValueError(F'''Input channels ({in_channels}) are not divisible by {groups} groups.'''   )
							if out_channels % groups != 0:
											raise ValueError(F'''Output channels ({out_channels}) are not divisible by {groups} groups.'''   )

							snake_case_						:   str           =  0 if config.tf_padding else int((kernel_size - 1) / 2   )

							snake_case_						:   List[Any]           =  nn.Convad(
							    in_channels=__magic_name__ ,							out_channels=__magic_name__ ,							kernel_size=__magic_name__ ,							stride=__magic_name__ ,							padding=__magic_name__ ,							groups=__magic_name__ ,							bias=__magic_name__ ,							padding_mode='''zeros''' ,							)

							if use_normalization:
											snake_case_						:   List[Any]           =  nn.BatchNormad(
											    num_features=__magic_name__ ,							eps=config.layer_norm_eps ,							momentum=0.9_997 ,							affine=__magic_name__ ,							track_running_stats=__magic_name__ ,							)
							else:
											snake_case_						:   Union[str, Any]           =  None

							if use_activation:
											if isinstance(__magic_name__ ,							__magic_name__   ):
															snake_case_						:   Any           =  ACTaFN[use_activation]
											elif isinstance(config.hidden_act ,							__magic_name__   ):
															snake_case_						:   int           =  ACTaFN[config.hidden_act]
											else:
															snake_case_						:   int           =  config.hidden_act
							else:
											snake_case_						:   int           =  None






			def       lowerCamelCase  (self ,							__magic_name__   )					->       torch.Tensor:


							'''simple docstring'''



							if self.config.tf_padding:
											snake_case_						:   List[Any]           =  apply_tf_padding(__magic_name__ ,							self.convolution   )
							snake_case_						:   Any           =  self.convolution(__magic_name__   )
							if self.normalization is not None:
											snake_case_						:   Union[str, Any]           =  self.normalization(__magic_name__   )
							if self.activation is not None:
											snake_case_						:   int           =  self.activation(__magic_name__   )
							return features




class  __lowerCAmelCase	(      _a					):
			lowerCamelCase_					:					List[str]	      =				MobileNetVaConfig
			lowerCamelCase_					:					int	      =				load_tf_weights_in_mobilenet_va
			lowerCamelCase_					:					Dict	      =				'''mobilenet_v1'''
			lowerCamelCase_					:					Optional[Any]	      =				'''pixel_values'''
			lowerCamelCase_					:					Optional[Any]	      =				False






			def       lowerCamelCase  (self ,							__magic_name__   )					->       None:


							'''simple docstring'''



							if isinstance(__magic_name__ ,							(nn.Linear, nn.Convad)   ):
											module.weight.data.normal_(mean=0.0 ,							std=self.config.initializer_range   )
											if module.bias is not None:
															module.bias.data.zero_()
							elif isinstance(__magic_name__ ,							nn.BatchNormad   ):
											module.bias.data.zero_()
											module.weight.data.fill_(1.0   )




lowerCAmelCase_    =    r'''
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''

lowerCAmelCase_    =    r'''
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`MobileNetV1ImageProcessor.__call__`] for details.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
'''



@add_start_docstrings(
    '''The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.''',					_a,					)
class  __lowerCAmelCase	(      _a					):






			def __init__(self ,							__magic_name__ ,							__magic_name__ = True   )					->       Optional[Any]:


							'''simple docstring'''



							super().__init__(__magic_name__   )
							snake_case_						:   Any           =  config

							snake_case_						:   Optional[Any]           =  32
							snake_case_						:   str           =  max(int(depth * config.depth_multiplier   ) ,							config.min_depth   )

							snake_case_						:   Any           =  MobileNetVaConvLayer(
							    __magic_name__ ,							in_channels=config.num_channels ,							out_channels=__magic_name__ ,							kernel_size=3 ,							stride=2 ,							)

							snake_case_						:   Optional[Any]           =  [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

							snake_case_						:   Tuple           =  nn.ModuleList()
							for i in range(13   ):
											snake_case_						:   Optional[Any]           =  out_channels

											if strides[i] == 2 or i == 0:
															depth *= 2
															snake_case_						:   List[str]           =  max(int(depth * config.depth_multiplier   ) ,							config.min_depth   )

											self.layer.append(
											    MobileNetVaConvLayer(
											        __magic_name__ ,							in_channels=__magic_name__ ,							out_channels=__magic_name__ ,							kernel_size=3 ,							stride=strides[i] ,							groups=__magic_name__ ,							)   )

											self.layer.append(
											    MobileNetVaConvLayer(
											        __magic_name__ ,							in_channels=__magic_name__ ,							out_channels=__magic_name__ ,							kernel_size=1 ,							)   )

							snake_case_						:   List[str]           =  nn.AdaptiveAvgPoolad((1, 1)   ) if add_pooling_layer else None

							# Initialize weights and apply final processing
							self.post_init()






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


							'''simple docstring'''



							raise NotImplementedError






			@add_start_docstrings_to_model_forward(__magic_name__   )
			@add_code_sample_docstrings(
			    checkpoint=_CHECKPOINT_FOR_DOC ,							output_type=__magic_name__ ,							config_class=_CONFIG_FOR_DOC ,							modality='''vision''' ,							expected_output=_EXPECTED_OUTPUT_SHAPE ,							)
			def       lowerCamelCase  (self ,							__magic_name__ = None ,							__magic_name__ = None ,							__magic_name__ = None ,							)					->       Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:


							'''simple docstring'''



							snake_case_						:   Dict           =  (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							snake_case_						:   Dict           =  return_dict if return_dict is not None else self.config.use_return_dict

							if pixel_values is None:
											raise ValueError('''You have to specify pixel_values'''   )

							snake_case_						:   List[Any]           =  self.conv_stem(__magic_name__   )

							snake_case_						:   int           =  () if output_hidden_states else None

							for i, layer_module in enumerate(self.layer   ):
											snake_case_						:   int           =  layer_module(__magic_name__   )

											if output_hidden_states:
															snake_case_						:   Optional[Any]           =  all_hidden_states + (hidden_states,)

							snake_case_						:   Any           =  hidden_states

							if self.pooler is not None:
											snake_case_						:   Dict           =  torch.flatten(self.pooler(__magic_name__   ) ,							start_dim=1   )
							else:
											snake_case_						:   Optional[int]           =  None

							if not return_dict:
											return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None   )

							return BaseModelOutputWithPoolingAndNoAttention(
							    last_hidden_state=__magic_name__ ,							pooler_output=__magic_name__ ,							hidden_states=__magic_name__ ,							)




@add_start_docstrings(
    '''
    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    ''',					_a,					)
class  __lowerCAmelCase	(      _a					):






			def __init__(self ,							__magic_name__   )					->       None:


							'''simple docstring'''



							super().__init__(__magic_name__   )

							snake_case_						:   Any           =  config.num_labels
							snake_case_						:   int           =  MobileNetVaModel(__magic_name__   )

							snake_case_						:   Any           =  self.mobilenet_va.layer[-1].convolution.out_channels

							# Classifier head
							snake_case_						:   str           =  nn.Dropout(config.classifier_dropout_prob ,							inplace=__magic_name__   )
							snake_case_						:   List[str]           =  nn.Linear(__magic_name__ ,							config.num_labels   ) if config.num_labels > 0 else nn.Identity()

							# Initialize weights and apply final processing
							self.post_init()






			@add_start_docstrings_to_model_forward(__magic_name__   )
			@add_code_sample_docstrings(
			    checkpoint=_IMAGE_CLASS_CHECKPOINT ,							output_type=__magic_name__ ,							config_class=_CONFIG_FOR_DOC ,							expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,							)
			def       lowerCamelCase  (self ,							__magic_name__ = None ,							__magic_name__ = None ,							__magic_name__ = None ,							__magic_name__ = None ,							)					->       Union[tuple, ImageClassifierOutputWithNoAttention]:


							'''simple docstring'''



							snake_case_						:   Optional[Any]           =  return_dict if return_dict is not None else self.config.use_return_dict

							snake_case_						:   List[Any]           =  self.mobilenet_va(__magic_name__ ,							output_hidden_states=__magic_name__ ,							return_dict=__magic_name__   )

							snake_case_						:   Tuple           =  outputs.pooler_output if return_dict else outputs[1]

							snake_case_						:   Union[str, Any]           =  self.classifier(self.dropout(__magic_name__   )   )

							snake_case_						:   List[Any]           =  None
							if labels is not None:
											if self.config.problem_type is None:
															if self.num_labels == 1:
																			snake_case_						:   Dict           =  '''regression'''
															elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																			snake_case_						:   Dict           =  '''single_label_classification'''
															else:
																			snake_case_						:   List[Any]           =  '''multi_label_classification'''

											if self.config.problem_type == "regression":
															snake_case_						:   Any           =  MSELoss()
															if self.num_labels == 1:
																			snake_case_						:   int           =  loss_fct(logits.squeeze() ,							labels.squeeze()   )
															else:
																			snake_case_						:   Tuple           =  loss_fct(__magic_name__ ,							__magic_name__   )
											elif self.config.problem_type == "single_label_classification":
															snake_case_						:   List[str]           =  CrossEntropyLoss()
															snake_case_						:   List[Any]           =  loss_fct(logits.view(-1 ,							self.num_labels   ) ,							labels.view(-1   )   )
											elif self.config.problem_type == "multi_label_classification":
															snake_case_						:   List[Any]           =  BCEWithLogitsLoss()
															snake_case_						:   int           =  loss_fct(__magic_name__ ,							__magic_name__   )

							if not return_dict:
											snake_case_						:   Dict           =  (logits,) + outputs[2:]
											return ((loss,) + output) if loss is not None else output

							return ImageClassifierOutputWithNoAttention(
							    loss=__magic_name__ ,							logits=__magic_name__ ,							hidden_states=outputs.hidden_states ,							)







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__   )
