




'''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   __UpperCamelCase       :
       lowercase	:    Union[str, Any]      						=XGLMConfig
       lowercase	:    Optional[Any]      						={}
       lowercase	:    Optional[int]      						='gelu'






       def __init__(							self,		lowerCAmelCase,		lowerCAmelCase=14,		lowerCAmelCase=7,		lowerCAmelCase=True,		lowerCAmelCase=True,		lowerCAmelCase=True,		lowerCAmelCase=99,		lowerCAmelCase=32,		lowerCAmelCase=2,		lowerCAmelCase=4,		lowerCAmelCase=37,		lowerCAmelCase="gelu",		lowerCAmelCase=0.1,		lowerCAmelCase=0.1,		lowerCAmelCase=512,		lowerCAmelCase=0.0_2,		):



              """simple docstring"""







              lowerCamelCase_							=parent
              lowerCamelCase_							=batch_size
              lowerCamelCase_							=seq_length
              lowerCamelCase_							=is_training
              lowerCamelCase_							=use_input_mask
              lowerCamelCase_							=use_labels
              lowerCamelCase_							=vocab_size
              lowerCamelCase_							=d_model
              lowerCamelCase_							=num_hidden_layers
              lowerCamelCase_							=num_attention_heads
              lowerCamelCase_							=ffn_dim
              lowerCamelCase_							=activation_function
              lowerCamelCase_							=activation_dropout
              lowerCamelCase_							=attention_dropout
              lowerCamelCase_							=max_position_embeddings
              lowerCamelCase_							=initializer_range
              lowerCamelCase_							=None
              lowerCamelCase_							=0
              lowerCamelCase_							=2
              lowerCamelCase_							=1






       def      lowercase__     (							self  ):



              """simple docstring"""







              return XGLMConfig.from_pretrained('''facebook/xglm-564M'''  )






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=tf.clip_by_value(
                  ids_tensor([self.batch_size, self.seq_length],		self.vocab_size  ),		clip_value_min=0,		clip_value_max=3  )

              lowerCamelCase_							=None
              if self.use_input_mask:
                     lowerCamelCase_							=random_attention_mask([self.batch_size, self.seq_length]  )

              lowerCamelCase_							=self.get_config()

              lowerCamelCase_							=floats_tensor([self.num_hidden_layers, self.num_attention_heads],		2  )

              return (
                  config,
                  input_ids,
                  input_mask,
                  head_mask,
              )






       def      lowercase__     (							self  ):



              """simple docstring"""







              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=lowerCAmelCase,		bos_token_id=self.bos_token_id,		eos_token_id=self.eos_token_id,		pad_token_id=self.pad_token_id,		return_dict=lowerCAmelCase,		)






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=self.prepare_config_and_inputs()

              (
                  (
                  lowerCamelCase_
              ),      (
                  lowerCamelCase_
              ),      (
                  lowerCamelCase_
              ),      (
                  lowerCamelCase_
              ),      
              )							=config_and_inputs

              lowerCamelCase_							={
                  '''input_ids''': input_ids,
                  '''head_mask''': head_mask,
              }

              return config, inputs_dict





@require_tf
class   __UpperCamelCase       ( lowerCamelCase__			,					lowerCamelCase__			,					unittest.TestCase				):
       lowercase	:    int      						=(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
       lowercase	:    Optional[Any]      						=(TFXGLMForCausalLM,) if is_tf_available() else ()
       lowercase	:    Tuple      						=(
           {'feature-extraction': TFXGLMModel, 'text-generation': TFXGLMForCausalLM} if is_tf_available() else {}
       )
       lowercase	:    Optional[Any]      						=False
       lowercase	:    Optional[Any]      						=False
       lowercase	:    Optional[int]      						=False






       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=TFXGLMModelTester(self  )
              lowerCamelCase_							=ConfigTester(self,		config_class=lowerCAmelCase,		n_embd=37  )






       def      lowercase__     (							self  ):



              """simple docstring"""







              self.config_tester.run_common_tests()






       @slow
       def      lowercase__     (							self  ):



              """simple docstring"""







              for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     lowerCamelCase_							=TFXGLMModel.from_pretrained(lowerCAmelCase  )
                     self.assertIsNotNone(lowerCAmelCase  )






       @unittest.skip(reason='''Currently, model embeddings are going to undergo a major refactor.'''  )
       def      lowercase__     (							self  ):



              """simple docstring"""







              super().test_resize_token_embeddings()





@require_tf
class   __UpperCamelCase       ( unittest.TestCase				):






       @slow
       def      lowercase__     (							self,		lowerCAmelCase=True  ):



              """simple docstring"""







              lowerCamelCase_							=TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''  )
              lowerCamelCase_							=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
              lowerCamelCase_							=[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
              lowerCamelCase_							=model.generate(lowerCAmelCase,		do_sample=lowerCAmelCase,		num_beams=1  )
              if verify_outputs:
                     self.assertListEqual(output_ids[0].numpy().tolist(),		lowerCAmelCase  )






       @slow
       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''  )
              lowerCamelCase_							=TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''  )

              tf.random.set_seed(0  )
              lowerCamelCase_							=tokenizer('''Today is a nice day and''',		return_tensors='''tf'''  )
              lowerCamelCase_							=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'''  ):
                     lowerCamelCase_							=model.generate(lowerCAmelCase,		do_sample=lowerCAmelCase,		seed=[7, 0]  )
              lowerCamelCase_							=tokenizer.decode(output_ids[0],		skip_special_tokens=lowerCAmelCase  )

              lowerCamelCase_							=(
                  '''Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due'''
              )
              self.assertEqual(lowerCAmelCase,		lowerCAmelCase  )






       @slow
       def      lowercase__     (							self  ):



              """simple docstring"""







              lowerCamelCase_							=TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''  )
              lowerCamelCase_							=XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''  )

              lowerCamelCase_							='''left'''

              # use different length sentences to test batching
              lowerCamelCase_							=[
                  '''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''',
              ]

              lowerCamelCase_							=tokenizer(lowerCAmelCase,		return_tensors='''tf''',		padding=lowerCAmelCase  )
              lowerCamelCase_							=inputs['''input_ids''']

              lowerCamelCase_							=model.generate(input_ids=lowerCAmelCase,		attention_mask=inputs['''attention_mask'''],		max_new_tokens=12  )

              lowerCamelCase_							=tokenizer(sentences[0],		return_tensors='''tf'''  ).input_ids
              lowerCamelCase_							=model.generate(input_ids=lowerCAmelCase,		max_new_tokens=12  )

              lowerCamelCase_							=tokenizer(sentences[1],		return_tensors='''tf'''  ).input_ids
              lowerCamelCase_							=model.generate(input_ids=lowerCAmelCase,		max_new_tokens=12  )

              lowerCamelCase_							=tokenizer.batch_decode(lowerCAmelCase,		skip_special_tokens=lowerCAmelCase  )
              lowerCamelCase_							=tokenizer.decode(output_non_padded[0],		skip_special_tokens=lowerCAmelCase  )
              lowerCamelCase_							=tokenizer.decode(output_padded[0],		skip_special_tokens=lowerCAmelCase  )

              lowerCamelCase_							=[
                  '''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(lowerCAmelCase,		lowerCAmelCase  )
              self.assertListEqual(lowerCAmelCase,		[non_padded_sentence, padded_sentence]  )








"""simple docstring"""




import os
import tempfile
from functools import partial
from unittest import TestCase
from unittest.mock import patch

import datasets
import datasets.config

from .utils import require_beam
class 					lowerCAmelCase	(					datasets.BeamBasedBuilder    ):




		'''simple docstring'''







		def 							__A						(	self				)     ->							Dict:
								return datasets.DatasetInfo(
								    features=datasets.Features({'content': datasets.Value('string'				)}				)						,       supervised_keys=lowerCAmelCase__						,       )







		def 							__A						(	self						,       lowerCAmelCase__						,       lowerCAmelCase__				)     ->							str:
								return [datasets.SplitGenerator(name=datasets.Split.TRAIN						,       gen_kwargs={'examples': get_test_dummy_examples()}				)]







		def 							__A						(	self						,       lowerCAmelCase__						,       lowerCAmelCase__				)     ->							Optional[int]:
								import apache_beam as beam

								return pipeline | "Load Examples" >> beam.Create(lowerCAmelCase__				)





class 					lowerCAmelCase	(					datasets.BeamBasedBuilder    ):




		'''simple docstring'''







		def 							__A						(	self				)     ->							int:
								return datasets.DatasetInfo(
								    features=datasets.Features({'a': datasets.Sequence({'b': datasets.Value('string'				)}				)}				)						,       supervised_keys=lowerCAmelCase__						,       )







		def 							__A						(	self						,       lowerCAmelCase__						,       lowerCAmelCase__				)     ->							Dict:
								return [
								    datasets.SplitGenerator(name=datasets.Split.TRAIN						,       gen_kwargs={'examples': get_test_nested_examples()}				)
								]







		def 							__A						(	self						,       lowerCAmelCase__						,       lowerCAmelCase__				)     ->							Optional[Any]:
								import apache_beam as beam

								return pipeline | "Load Examples" >> beam.Create(lowerCAmelCase__				)





def     lowercase			()   ->						str:
						return [(i, {"content": content}) for i, content in enumerate(['foo', 'bar', 'foobar']  )]


def     lowercase			()   ->						Optional[Any]:
						return [(i, {"a": {"b": [content]}}) for i, content in enumerate(['foo', 'bar', 'foobar']  )]


class 					lowerCAmelCase	(					lowerCamelCase_    ):




		'''simple docstring'''







		@require_beam
		def 							__A						(	self				)     ->							Optional[int]:
								SCREAMING_SNAKE_CASE													=					len(get_test_dummy_examples()				)
								with tempfile.TemporaryDirectory() as tmp_cache_dir:
														SCREAMING_SNAKE_CASE													=					DummyBeamDataset(cache_dir=lowerCAmelCase__						,       beam_runner='DirectRunner'				)
														builder.download_and_prepare()
														self.assertTrue(
														    os.path.exists(
														        os.path.join(lowerCAmelCase__						,       builder.name						,       'default'						,       '0.0.0'						,       F'{builder.name}-train.arrow'				)				)				)
														self.assertDictEqual(builder.info.features						,       datasets.Features({'content': datasets.Value('string'				)}				)				)
														SCREAMING_SNAKE_CASE													=					builder.as_dataset()
														self.assertEqual(dset['train'].num_rows						,       lowerCAmelCase__				)
														self.assertEqual(dset['train'].info.splits['train'].num_examples						,       lowerCAmelCase__				)
														self.assertDictEqual(dset['train'][0]						,       get_test_dummy_examples()[0][1]				)
														self.assertDictEqual(
														    dset['train'][expected_num_examples - 1]						,       get_test_dummy_examples()[expected_num_examples - 1][1]				)
														self.assertTrue(
														    os.path.exists(os.path.join(lowerCAmelCase__						,       builder.name						,       'default'						,       '0.0.0'						,       'dataset_info.json'				)				)				)
														del dset







		@require_beam
		def 							__A						(	self				)     ->							int:
								import apache_beam as beam

								SCREAMING_SNAKE_CASE													=					beam.io.parquetio.WriteToParquet

								SCREAMING_SNAKE_CASE													=					len(get_test_dummy_examples()				)
								with tempfile.TemporaryDirectory() as tmp_cache_dir:
														SCREAMING_SNAKE_CASE													=					DummyBeamDataset(cache_dir=lowerCAmelCase__						,       beam_runner='DirectRunner'				)
														with patch('apache_beam.io.parquetio.WriteToParquet'				) as write_parquet_mock:
																				SCREAMING_SNAKE_CASE													=					partial(lowerCAmelCase__						,       num_shards=2				)
																				builder.download_and_prepare()
														self.assertTrue(
														    os.path.exists(
														        os.path.join(
														            lowerCAmelCase__						,       builder.name						,       'default'						,       '0.0.0'						,       F'{builder.name}-train-00000-of-00002.arrow'				)				)				)
														self.assertTrue(
														    os.path.exists(
														        os.path.join(
														            lowerCAmelCase__						,       builder.name						,       'default'						,       '0.0.0'						,       F'{builder.name}-train-00000-of-00002.arrow'				)				)				)
														self.assertDictEqual(builder.info.features						,       datasets.Features({'content': datasets.Value('string'				)}				)				)
														SCREAMING_SNAKE_CASE													=					builder.as_dataset()
														self.assertEqual(dset['train'].num_rows						,       lowerCAmelCase__				)
														self.assertEqual(dset['train'].info.splits['train'].num_examples						,       lowerCAmelCase__				)
														# Order is not preserved when sharding, so we just check that all the elements are there
														self.assertListEqual(sorted(dset['train']['content']				)						,       sorted(['foo', 'bar', 'foobar']				)				)
														self.assertTrue(
														    os.path.exists(os.path.join(lowerCAmelCase__						,       builder.name						,       'default'						,       '0.0.0'						,       'dataset_info.json'				)				)				)
														del dset







		@require_beam
		def 							__A						(	self				)     ->							Optional[Any]:
								with tempfile.TemporaryDirectory() as tmp_cache_dir:
														SCREAMING_SNAKE_CASE													=					DummyBeamDataset(cache_dir=lowerCAmelCase__				)
														self.assertRaises(datasets.builder.MissingBeamOptions						,       builder.download_and_prepare				)







		@require_beam
		def 							__A						(	self				)     ->							int:
								SCREAMING_SNAKE_CASE													=					len(get_test_nested_examples()				)
								with tempfile.TemporaryDirectory() as tmp_cache_dir:
														SCREAMING_SNAKE_CASE													=					NestedBeamDataset(cache_dir=lowerCAmelCase__						,       beam_runner='DirectRunner'				)
														builder.download_and_prepare()
														self.assertTrue(
														    os.path.exists(
														        os.path.join(lowerCAmelCase__						,       builder.name						,       'default'						,       '0.0.0'						,       F'{builder.name}-train.arrow'				)				)				)
														self.assertDictEqual(
														    builder.info.features						,       datasets.Features({'a': datasets.Sequence({'b': datasets.Value('string'				)}				)}				)				)
														SCREAMING_SNAKE_CASE													=					builder.as_dataset()
														self.assertEqual(dset['train'].num_rows						,       lowerCAmelCase__				)
														self.assertEqual(dset['train'].info.splits['train'].num_examples						,       lowerCAmelCase__				)
														self.assertDictEqual(dset['train'][0]						,       get_test_nested_examples()[0][1]				)
														self.assertDictEqual(
														    dset['train'][expected_num_examples - 1]						,       get_test_nested_examples()[expected_num_examples - 1][1]				)
														self.assertTrue(
														    os.path.exists(os.path.join(lowerCAmelCase__						,       builder.name						,       'default'						,       '0.0.0'						,       'dataset_info.json'				)				)				)
														del dset


