






'''simple docstring'''





from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
	import tensorflow as tf

	from transformers.models.xglm.modeling_tf_xglm import (
	    TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
	    TFXGLMForCausalLM,
	    TFXGLMModel,
	)


@require_tf
class 					_snake_case						:
	_A          =   XGLMConfig
	_A          =   {}
	_A          =   'gelu'






	def __init__(		self					,UpperCamelCase					,UpperCamelCase=14					,UpperCamelCase=7					,UpperCamelCase=True					,UpperCamelCase=True					,UpperCamelCase=True					,UpperCamelCase=99					,UpperCamelCase=32					,UpperCamelCase=2					,UpperCamelCase=4					,UpperCamelCase=37					,UpperCamelCase="gelu"					,UpperCamelCase=0.1					,UpperCamelCase=0.1					,UpperCamelCase=512					,UpperCamelCase=0.02					,)						->    Optional[int]:
					snake_case__      :List[str]         =   parent
					snake_case__      :List[Any]         =   batch_size
					snake_case__      :Optional[Any]         =   seq_length
					snake_case__      :Any         =   is_training
					snake_case__      :List[str]         =   use_input_mask
					snake_case__      :List[Any]         =   use_labels
					snake_case__      :str         =   vocab_size
					snake_case__      :Dict         =   d_model
					snake_case__      :str         =   num_hidden_layers
					snake_case__      :Optional[int]         =   num_attention_heads
					snake_case__      :List[str]         =   ffn_dim
					snake_case__      :Any         =   activation_function
					snake_case__      :Union[str, Any]         =   activation_dropout
					snake_case__      :List[str]         =   attention_dropout
					snake_case__      :Optional[int]         =   max_position_embeddings
					snake_case__      :List[str]         =   initializer_range
					snake_case__      :Any         =   None
					snake_case__      :str         =   0
					snake_case__      :List[Any]         =   2
					snake_case__      :List[Any]         =   1






	def    lowerCAmelCase_							(		self       )						->    int:
					return XGLMConfig.from_pretrained("facebook/xglm-564M"       )






	def    lowerCAmelCase_							(		self       )						->    str:
					snake_case__      :Optional[Any]         =   tf.clip_by_value(
					    ids_tensor([self.batch_size, self.seq_length]					,self.vocab_size       )					,clip_value_min=0					,clip_value_max=3       )

					snake_case__      :Union[str, Any]         =   None
					if self.use_input_mask:
									snake_case__      :Dict         =   random_attention_mask([self.batch_size, self.seq_length]       )

					snake_case__      :Union[str, Any]         =   self.get_config()

					snake_case__      :Tuple         =   floats_tensor([self.num_hidden_layers, self.num_attention_heads]					,2       )

					return (
					    config,
					    input_ids,
					    input_mask,
					    head_mask,
					)






	def    lowerCAmelCase_							(		self       )						->    Dict:
					return XGLMConfig(
					    vocab_size=self.vocab_size					,d_model=self.hidden_size					,num_layers=self.num_hidden_layers					,attention_heads=self.num_attention_heads					,ffn_dim=self.ffn_dim					,activation_function=self.activation_function					,activation_dropout=self.activation_dropout					,attention_dropout=self.attention_dropout					,max_position_embeddings=self.max_position_embeddings					,initializer_range=self.initializer_range					,use_cache=UpperCamelCase					,bos_token_id=self.bos_token_id					,eos_token_id=self.eos_token_id					,pad_token_id=self.pad_token_id					,return_dict=UpperCamelCase					,)






	def    lowerCAmelCase_							(		self       )						->    List[str]:
					snake_case__      :Union[str, Any]         =   self.prepare_config_and_inputs()

					(
					    snake_case__						
					)      :List[str]         =   config_and_inputs

					snake_case__      :List[Any]         =   {
					    "input_ids": input_ids,
					    "head_mask": head_mask,
					}

					return config, inputs_dict




@require_tf
class 					_snake_case						(			_A       ,    _A       ,    unittest.TestCase ):
	_A          =   (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
	_A          =   (TFXGLMForCausalLM,) if is_tf_available() else ()
	_A          =   (
	    {'feature-extraction': TFXGLMModel, 'text-generation': TFXGLMForCausalLM} if is_tf_available() else {}
	)
	_A          =   False
	_A          =   False
	_A          =   False






	def    lowerCAmelCase_							(		self       )						->    List[str]:
					snake_case__      :Optional[Any]         =   TFXGLMModelTester(self       )
					snake_case__      :Optional[int]         =   ConfigTester(self					,config_class=UpperCamelCase					,n_embd=37       )






	def    lowerCAmelCase_							(		self       )						->    Optional[int]:
					self.config_tester.run_common_tests()






	@slow
	def    lowerCAmelCase_							(		self       )						->    List[Any]:
					for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									snake_case__      :List[Any]         =   TFXGLMModel.from_pretrained(UpperCamelCase       )
									self.assertIsNotNone(UpperCamelCase       )






	@unittest.skip(reason="Currently, model embeddings are going to undergo a major refactor."       )
	def    lowerCAmelCase_							(		self       )						->    List[str]:
					super().test_resize_token_embeddings()




@require_tf
class 					_snake_case						(			unittest.TestCase ):






	@slow
	def    lowerCAmelCase_							(		self					,UpperCamelCase=True       )						->    str:
					snake_case__      :str         =   TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M"       )
					snake_case__      :Optional[Any]         =   tf.convert_to_tensor([[2, 268, 9_865]]					,dtype=tf.intaa       )  # The dog
					# </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
					# fmt: off
					snake_case__      :Any         =   [2, 268, 9_865, 67, 11, 1_988, 57_252, 9_865, 5, 984, 67, 1_988, 213_838, 1_658, 53, 70_446, 33, 6_657, 278, 1_581]
					# fmt: on
					snake_case__      :Dict         =   model.generate(UpperCamelCase					,do_sample=UpperCamelCase					,num_beams=1       )
					if verify_outputs:
									self.assertListEqual(output_ids[0].numpy().tolist()					,UpperCamelCase       )






	@slow
	def    lowerCAmelCase_							(		self       )						->    Tuple:
					snake_case__      :str         =   XGLMTokenizer.from_pretrained("facebook/xglm-564M"       )
					snake_case__      :Tuple         =   TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M"       )

					tf.random.set_seed(0       )
					snake_case__      :Optional[int]         =   tokenizer("Today is a nice day and"					,return_tensors="tf"       )
					snake_case__      :int         =   tokenized.input_ids
					# forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
					with tf.device(":/CPU:0"       ):
									snake_case__      :Tuple         =   model.generate(UpperCamelCase					,do_sample=UpperCamelCase					,seed=[7, 0]       )
					snake_case__      :str         =   tokenizer.decode(output_ids[0]					,skip_special_tokens=UpperCamelCase       )

					snake_case__      :str         =   (
					    "Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due"
					)
					self.assertEqual(UpperCamelCase					,UpperCamelCase       )






	@slow
	def    lowerCAmelCase_							(		self       )						->    List[Any]:
					snake_case__      :str         =   TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M"       )
					snake_case__      :str         =   XGLMTokenizer.from_pretrained("facebook/xglm-564M"       )

					snake_case__      :Any         =   "left"

					# use different length sentences to test batching
					snake_case__      :List[str]         =   [
					    "This is an extremelly long sentence that only exists to test the ability of the model to cope with "
					    "left-padding, such as in batched generation. The output for the sequence below should be the same "
					    "regardless of whether left padding is applied or not. When",
					    "Hello, my dog is a little",
					]

					snake_case__      :Optional[int]         =   tokenizer(UpperCamelCase					,return_tensors="tf"					,padding=UpperCamelCase       )
					snake_case__      :Dict         =   inputs["input_ids"]

					snake_case__      :Any         =   model.generate(input_ids=UpperCamelCase					,attention_mask=inputs["attention_mask"]					,max_new_tokens=12       )

					snake_case__      :Any         =   tokenizer(sentences[0]					,return_tensors="tf"       ).input_ids
					snake_case__      :str         =   model.generate(input_ids=UpperCamelCase					,max_new_tokens=12       )

					snake_case__      :Union[str, Any]         =   tokenizer(sentences[1]					,return_tensors="tf"       ).input_ids
					snake_case__      :str         =   model.generate(input_ids=UpperCamelCase					,max_new_tokens=12       )

					snake_case__      :List[Any]         =   tokenizer.batch_decode(UpperCamelCase					,skip_special_tokens=UpperCamelCase       )
					snake_case__      :Optional[int]         =   tokenizer.decode(output_non_padded[0]					,skip_special_tokens=UpperCamelCase       )
					snake_case__      :List[str]         =   tokenizer.decode(output_padded[0]					,skip_special_tokens=UpperCamelCase       )

					snake_case__      :Any         =   [
					    "This is an extremelly long sentence that only exists to test the ability of the model to cope with "
					    "left-padding, such as in batched generation. The output for the sequence below should be the same "
					    "regardless of whether left padding is applied or not. When left padding is applied, the sequence will be "
					    "a single",
					    "Hello, my dog is a little bit of a shy one, but he is very friendly",
					]
					self.assertListEqual(UpperCamelCase					,UpperCamelCase       )
					self.assertListEqual(UpperCamelCase					,[non_padded_sentence, padded_sentence]       )







import json
import os
import shutil
import warnings
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import List

from ..utils import logging
from . import BaseTransformersCLICommand


try:
	from cookiecutter.main import cookiecutter

	__UpperCAmelCase							:   Dict							=  True
except ImportError:
	__UpperCAmelCase							:   List[Any]							=  False

__UpperCAmelCase							:   Dict							=  logging.get_logger(__name__)  # pylint: disable=invalid-name





def 					lowercase_ (    __snake_case     :							Namespace      )     -> Dict:





				'''simple docstring'''


				return AddNewModelCommand(args.testing	,	args.testing_file	,	path=args.path      )


class 					_snake_case						(			_A ):






	@staticmethod
	def    lowerCAmelCase_							(		UpperCamelCase       )						->    Any:
					snake_case__      :Dict         =   parser.add_parser("add-new-model"       )
					add_new_model_parser.add_argument("--testing"					,action="store_true"					,help="If in testing mode."       )
					add_new_model_parser.add_argument("--testing_file"					,type=UpperCamelCase					,help="Configuration file on which to run."       )
					add_new_model_parser.add_argument(
					    "--path"					,type=UpperCamelCase					,help="Path to cookiecutter. Should only be used for testing purposes."       )
					add_new_model_parser.set_defaults(func=UpperCamelCase       )






	def __init__(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase=None					,*UpperCamelCase       )						->    Any:
					snake_case__      :Union[str, Any]         =   testing
					snake_case__      :Union[str, Any]         =   testing_file
					snake_case__      :List[str]         =   path






	def    lowerCAmelCase_							(		self       )						->    List[Any]:
					warnings.warn(
					    "The command `transformers-cli add-new-model` is deprecated and will be removed in v5 of Transformers. "
					    "It is not actively maintained anymore, so might give a result that won't pass all tests and quality "
					    "checks, you should use `transformers-cli add-new-model-like` instead."       )
					if not _has_cookiecutter:
									raise ImportError(
									    "Model creation dependencies are required to use the `add_new_model` command. Install them by running "
									    "the following at the root of your `transformers` clone:\n\n\t$ pip install -e .[modelcreation]\n"       )
					# Ensure that there is no other `cookiecutter-template-xxx` directory in the current working directory
					snake_case__      :Tuple         =   [directory for directory in os.listdir() if "cookiecutter-template-" == directory[:22]]
					if len(UpperCamelCase       ) > 0:
									raise ValueError(
									    "Several directories starting with `cookiecutter-template-` in current working directory. "
									    "Please clean your directory by removing all folders starting with `cookiecutter-template-` or "
									    "change your working directory."       )

					snake_case__      :str         =   (
					    Path(UpperCamelCase       ).parent.parent.parent.parent if self._path is None else Path(self._path       ).parent.parent
					)
					snake_case__      :Tuple         =   path_to_transformer_root / "templates" / "adding_a_new_model"

					# Execute cookiecutter
					if not self._testing:
									cookiecutter(str(UpperCamelCase       )       )
					else:
									with open(self._testing_file					,"r"       ) as configuration_file:
													snake_case__      :str         =   json.load(UpperCamelCase       )

									cookiecutter(
									    str(path_to_cookiecutter if self._path is None else self._path       )					,no_input=UpperCamelCase					,extra_context=UpperCamelCase					,)

					snake_case__      :List[Any]         =   [directory for directory in os.listdir() if "cookiecutter-template-" in directory[:22]][0]

					# Retrieve configuration
					with open(directory + "/configuration.json"					,"r"       ) as configuration_file:
									snake_case__      :Dict         =   json.load(UpperCamelCase       )

					snake_case__      :Optional[Any]         =   configuration["lowercase_modelname"]
					snake_case__      :List[Any]         =   configuration["generate_tensorflow_pytorch_and_flax"]
					os.remove(f'{directory}/configuration.json'       )

					snake_case__      :Any         =   "PyTorch" in generate_tensorflow_pytorch_and_flax
					snake_case__      :Any         =   "TensorFlow" in generate_tensorflow_pytorch_and_flax
					snake_case__      :Any         =   "Flax" in generate_tensorflow_pytorch_and_flax

					snake_case__      :Dict         =   f'{path_to_transformer_root}/src/transformers/models/{lowercase_model_name}'
					os.makedirs(UpperCamelCase					,exist_ok=UpperCamelCase       )
					os.makedirs(f'{path_to_transformer_root}/tests/models/{lowercase_model_name}'					,exist_ok=UpperCamelCase       )

					# Tests require submodules as they have parent imports
					with open(f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/__init__.py'					,"w"       ):
									pass

					shutil.move(
					    f'{directory}/__init__.py'					,f'{model_dir}/__init__.py'					,)
					shutil.move(
					    f'{directory}/configuration_{lowercase_model_name}.py'					,f'{model_dir}/configuration_{lowercase_model_name}.py'					,)

					def remove_copy_lines(UpperCamelCase       ):
									with open(UpperCamelCase					,"r"       ) as f:
													snake_case__      :List[str]         =   f.readlines()
									with open(UpperCamelCase					,"w"       ) as f:
													for line in lines:
																	if "# Copied from transformers." not in line:
																					f.write(UpperCamelCase       )

					if output_pytorch:
									if not self._testing:
													remove_copy_lines(f'{directory}/modeling_{lowercase_model_name}.py'       )

									shutil.move(
									    f'{directory}/modeling_{lowercase_model_name}.py'					,f'{model_dir}/modeling_{lowercase_model_name}.py'					,)

									shutil.move(
									    f'{directory}/test_modeling_{lowercase_model_name}.py'					,f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_{lowercase_model_name}.py'					,)
					else:
									os.remove(f'{directory}/modeling_{lowercase_model_name}.py'       )
									os.remove(f'{directory}/test_modeling_{lowercase_model_name}.py'       )

					if output_tensorflow:
									if not self._testing:
													remove_copy_lines(f'{directory}/modeling_tf_{lowercase_model_name}.py'       )

									shutil.move(
									    f'{directory}/modeling_tf_{lowercase_model_name}.py'					,f'{model_dir}/modeling_tf_{lowercase_model_name}.py'					,)

									shutil.move(
									    f'{directory}/test_modeling_tf_{lowercase_model_name}.py'					,f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_tf_{lowercase_model_name}.py'					,)
					else:
									os.remove(f'{directory}/modeling_tf_{lowercase_model_name}.py'       )
									os.remove(f'{directory}/test_modeling_tf_{lowercase_model_name}.py'       )

					if output_flax:
									if not self._testing:
													remove_copy_lines(f'{directory}/modeling_flax_{lowercase_model_name}.py'       )

									shutil.move(
									    f'{directory}/modeling_flax_{lowercase_model_name}.py'					,f'{model_dir}/modeling_flax_{lowercase_model_name}.py'					,)

									shutil.move(
									    f'{directory}/test_modeling_flax_{lowercase_model_name}.py'					,f'{path_to_transformer_root}/tests/models/{lowercase_model_name}/test_modeling_flax_{lowercase_model_name}.py'					,)
					else:
									os.remove(f'{directory}/modeling_flax_{lowercase_model_name}.py'       )
									os.remove(f'{directory}/test_modeling_flax_{lowercase_model_name}.py'       )

					shutil.move(
					    f'{directory}/{lowercase_model_name}.md'					,f'{path_to_transformer_root}/docs/source/en/model_doc/{lowercase_model_name}.md'					,)

					shutil.move(
					    f'{directory}/tokenization_{lowercase_model_name}.py'					,f'{model_dir}/tokenization_{lowercase_model_name}.py'					,)

					shutil.move(
					    f'{directory}/tokenization_fast_{lowercase_model_name}.py'					,f'{model_dir}/tokenization_{lowercase_model_name}_fast.py'					,)

					from os import fdopen, remove
					from shutil import copymode, move
					from tempfile import mkstemp

					def replace(UpperCamelCase					,UpperCamelCase					,UpperCamelCase       ):
									# Create temp file
									snake_case__    ,						snake_case__      :Optional[Any]         =   mkstemp()
									snake_case__      :Optional[Any]         =   False
									with fdopen(UpperCamelCase					,"w"       ) as new_file:
													with open(UpperCamelCase       ) as old_file:
																	for line in old_file:
																					new_file.write(UpperCamelCase       )
																					if line_to_copy_below in line:
																									snake_case__      :Optional[Any]         =   True
																									for line_to_copy in lines_to_copy:
																													new_file.write(UpperCamelCase       )

									if not line_found:
													raise ValueError(f'Line {line_to_copy_below} was not found in file.'       )

									# Copy the file permissions from the old file to the new file
									copymode(UpperCamelCase					,UpperCamelCase       )
									# Remove original file
									remove(UpperCamelCase       )
									# Move new file
									move(UpperCamelCase					,UpperCamelCase       )

					def skip_units(UpperCamelCase       ):
									return (
									    ("generating PyTorch" in line and not output_pytorch)
									    or ("generating TensorFlow" in line and not output_tensorflow)
									    or ("generating Flax" in line and not output_flax)
									)

					def replace_in_files(UpperCamelCase       ):
									with open(UpperCamelCase       ) as datafile:
													snake_case__      :int         =   []
													snake_case__      :Optional[int]         =   False
													snake_case__      :List[str]         =   False
													for line in datafile:
																	if "# To replace in: " in line and "##" not in line:
																					snake_case__      :Optional[Any]         =   line.split("\""       )[1]
																					snake_case__      :Tuple         =   skip_units(UpperCamelCase       )
																	elif "# Below: " in line and "##" not in line:
																					snake_case__      :Optional[Any]         =   line.split("\""       )[1]
																					snake_case__      :List[str]         =   skip_units(UpperCamelCase       )
																	elif "# End." in line and "##" not in line:
																					if not skip_file and not skip_snippet:
																									replace(UpperCamelCase					,UpperCamelCase					,UpperCamelCase       )

																					snake_case__      :Tuple         =   []
																	elif "# Replace with" in line and "##" not in line:
																					snake_case__      :Optional[Any]         =   []
																	elif "##" not in line:
																					lines_to_copy.append(UpperCamelCase       )

									remove(UpperCamelCase       )

					replace_in_files(f'{directory}/to_replace_{lowercase_model_name}.py'       )
					os.rmdir(UpperCamelCase       )