



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_    :
							lowerCamelCase__   			=		XGLMConfig
							lowerCamelCase__   			=		{}
							lowerCamelCase__   			=		'gelu'







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

														'''simple docstring'''

														_lowerCAmelCase     :							Dict    =    parent
														_lowerCAmelCase     :							Tuple    =    batch_size
														_lowerCAmelCase     :							Dict    =    seq_length
														_lowerCAmelCase     :							Optional[int]    =    is_training
														_lowerCAmelCase     :							Optional[Any]    =    use_input_mask
														_lowerCAmelCase     :							Union[str, Any]    =    use_labels
														_lowerCAmelCase     :							Dict    =    vocab_size
														_lowerCAmelCase     :							List[str]    =    d_model
														_lowerCAmelCase     :							int    =    num_hidden_layers
														_lowerCAmelCase     :							List[Any]    =    num_attention_heads
														_lowerCAmelCase     :							int    =    ffn_dim
														_lowerCAmelCase     :							Any    =    activation_function
														_lowerCAmelCase     :							str    =    activation_dropout
														_lowerCAmelCase     :							List[Any]    =    attention_dropout
														_lowerCAmelCase     :							Dict    =    max_position_embeddings
														_lowerCAmelCase     :							Any    =    initializer_range
														_lowerCAmelCase     :							Optional[Any]    =    None
														_lowerCAmelCase     :							Any    =    0
														_lowerCAmelCase     :							Optional[Any]    =    2
														_lowerCAmelCase     :							Dict    =    1







							def    snake_case__      (   self):

														'''simple docstring'''

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







							def    snake_case__      (   self):

														'''simple docstring'''

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

														_lowerCAmelCase     :							Optional[Any]    =    None
														if self.use_input_mask:
																					_lowerCAmelCase     :							Optional[int]    =    random_attention_mask([self.batch_size, self.seq_length])

														_lowerCAmelCase     :							int    =    self.get_config()

														_lowerCAmelCase     :							Dict    =    floats_tensor([self.num_hidden_layers, self.num_attention_heads],			2)

														return (
														    config,
														    input_ids,
														    input_mask,
														    head_mask,
														)







							def    snake_case__      (   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=__a,			bos_token_id=self.bos_token_id,			eos_token_id=self.eos_token_id,			pad_token_id=self.pad_token_id,			return_dict=__a,			)







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[int]    =    self.prepare_config_and_inputs()

														(
														    (
														    _lowerCAmelCase
														)   ,    (
														    _lowerCAmelCase
														)   ,    (
														    _lowerCAmelCase
														)   ,    (
														    _lowerCAmelCase
														)   ,    
														)     :							List[Any]    =    config_and_inputs

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

														return config, inputs_dict



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







							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							List[str]    =    TFXGLMModelTester(self)
														_lowerCAmelCase     :							int    =    ConfigTester(self,			config_class=__a,			n_embd=37)







							def    snake_case__      (   self):

														'''simple docstring'''

														self.config_tester.run_common_tests()







							@slow
							def    snake_case__      (   self):

														'''simple docstring'''

														for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					_lowerCAmelCase     :							Any    =    TFXGLMModel.from_pretrained(__a)
																					self.assertIsNotNone(__a)







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

														'''simple docstring'''

														super().test_resize_token_embeddings()



@require_tf
class   UpperCAmelCase_    (       unittest.TestCase):







							@slow
							def    snake_case__      (   self,			__a=True):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[int]    =    TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M")
														_lowerCAmelCase     :							Optional[Any]    =    tf.convert_to_tensor([[2, 268, 9865]],			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     :							Tuple    =    [2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581]
														# fmt: on
														_lowerCAmelCase     :							Tuple    =    model.generate(__a,			do_sample=__a,			num_beams=1)
														if verify_outputs:
																					self.assertListEqual(output_ids[0].numpy().tolist(),			__a)







							@slow
							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Union[str, Any]    =    XGLMTokenizer.from_pretrained("facebook/xglm-564M")
														_lowerCAmelCase     :							List[str]    =    TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M")

														tf.random.set_seed(0)
														_lowerCAmelCase     :							Union[str, Any]    =    tokenizer("Today is a nice day and",			return_tensors="tf")
														_lowerCAmelCase     :							Union[str, Any]    =    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     :							Tuple    =    model.generate(__a,			do_sample=__a,			seed=[7, 0])
														_lowerCAmelCase     :							Optional[Any]    =    tokenizer.decode(output_ids[0],			skip_special_tokens=__a)

														_lowerCAmelCase     :							Optional[Any]    =    (
														    "Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due"
														)
														self.assertEqual(__a,			__a)







							@slow
							def    snake_case__      (   self):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[Any]    =    TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M")
														_lowerCAmelCase     :							Any    =    XGLMTokenizer.from_pretrained("facebook/xglm-564M")

														_lowerCAmelCase     :							Union[str, Any]    =    "left"

														# use different length sentences to test batching
														_lowerCAmelCase     :							Tuple    =    [
														    "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     :							Tuple    =    tokenizer(__a,			return_tensors="tf",			padding=__a)
														_lowerCAmelCase     :							List[str]    =    inputs["input_ids"]

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

														_lowerCAmelCase     :							List[Any]    =    tokenizer(sentences[0],			return_tensors="tf").input_ids
														_lowerCAmelCase     :							int    =    model.generate(input_ids=__a,			max_new_tokens=12)

														_lowerCAmelCase     :							List[Any]    =    tokenizer(sentences[1],			return_tensors="tf").input_ids
														_lowerCAmelCase     :							Optional[Any]    =    model.generate(input_ids=__a,			max_new_tokens=12)

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

														_lowerCAmelCase     :							Union[str, 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(__a,			__a)
														self.assertListEqual(__a,			[non_padded_sentence, padded_sentence])



import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


snake_case_			  = datasets.utils.logging.get_logger(__name__)

snake_case_			  = ['''names''', '''prefix''']
snake_case_			  = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols''']
snake_case_			  = ['''encoding_errors''', '''on_bad_lines''']
snake_case_			  = ['''date_format''']


@dataclass
class       SCREAMING_SNAKE_CASE__					(datasets.BuilderConfig     ):
    __lowerCamelCase						:       str														=     ","
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[Union[int, List[int], str]]														=     "infer"
    __lowerCamelCase						:       Optional[List[str]]														=     None
    __lowerCamelCase						:       Optional[List[str]]														=     None
    __lowerCamelCase						:       Optional[Union[int, str, List[int], List[str]]]														=     None
    __lowerCamelCase						:       Optional[Union[List[int], List[str]]]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       Optional[Literal["c", "python", "pyarrow"]]														=     None
    __lowerCamelCase						:       Dict[Union[int, str], Callable[[Any], Any]]														=     None
    __lowerCamelCase						:       Optional[list]														=     None
    __lowerCamelCase						:       Optional[list]														=     None
    __lowerCamelCase						:       bool														=     False
    __lowerCamelCase						:       Optional[Union[int, List[int]]]														=     None
    __lowerCamelCase						:       Optional[int]														=     None
    __lowerCamelCase						:       Optional[Union[str, List[str]]]														=     None
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       bool														=     False
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       str														=     "."
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       str														=     '"'
    __lowerCamelCase						:       int														=     0
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       int														=     0
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       bool														=     False
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       int														=     1_0000
    __lowerCamelCase						:       Optional[datasets.Features]														=     None
    __lowerCamelCase						:       Optional[str]														=     "strict"
    __lowerCamelCase						:       Literal["error", "warn", "skip"]														=     "error"
    __lowerCamelCase						:       Optional[str]														=     None





    def       snake_case_				(      self):
         if self.delimiter is not None:
              lowercase__    :   List[Any]      =       self.delimiter
         if self.column_names is not None:
              lowercase__    :   Optional[int]      =       self.column_names





    @property
    def       snake_case_				(      self):
         lowercase__    :   Dict      =       {
             'sep': self.sep,
             'header': self.header,
             'names': self.names,
             'index_col': self.index_col,
             'usecols': self.usecols,
             'prefix': self.prefix,
             'mangle_dupe_cols': self.mangle_dupe_cols,
             'engine': self.engine,
             'converters': self.converters,
             'true_values': self.true_values,
             'false_values': self.false_values,
             'skipinitialspace': self.skipinitialspace,
             'skiprows': self.skiprows,
             'nrows': self.nrows,
             'na_values': self.na_values,
             'keep_default_na': self.keep_default_na,
             'na_filter': self.na_filter,
             'verbose': self.verbose,
             'skip_blank_lines': self.skip_blank_lines,
             'thousands': self.thousands,
             'decimal': self.decimal,
             'lineterminator': self.lineterminator,
             'quotechar': self.quotechar,
             'quoting': self.quoting,
             'escapechar': self.escapechar,
             'comment': self.comment,
             'encoding': self.encoding,
             'dialect': self.dialect,
             'error_bad_lines': self.error_bad_lines,
             'warn_bad_lines': self.warn_bad_lines,
             'skipfooter': self.skipfooter,
             'doublequote': self.doublequote,
             'memory_map': self.memory_map,
             'float_precision': self.float_precision,
             'chunksize': self.chunksize,
             'encoding_errors': self.encoding_errors,
             'on_bad_lines': self.on_bad_lines,
             'date_format': self.date_format,
         }

         # some kwargs must not be passed if they don't have a default value
         # some others are deprecated and we can also not pass them if they are the default value
         for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
              if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()						,   a):
                   del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
         if not (datasets.config.PANDAS_VERSION.major >= 2):
              for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
                   del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
         if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
              for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
                   del pd_read_csv_kwargs[pd_read_csv_parameter]

         return pd_read_csv_kwargs



class       SCREAMING_SNAKE_CASE__					(datasets.ArrowBasedBuilder     ):
    __lowerCamelCase						:       Optional[Any]														=     CsvConfig





    def       snake_case_				(      self):
         return datasets.DatasetInfo(features=self.config.features)





    def       snake_case_				(      self						,   a):
         if not self.config.data_files:
              raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""")
         lowercase__    :   Any      =       dl_manager.download_and_extract(self.config.data_files)
         if isinstance(a						,   (str, list, tuple)):
              lowercase__    :   List[str]      =       data_files
              if isinstance(a						,   a):
                   lowercase__    :   Optional[Any]      =       [files]
              lowercase__    :   Optional[int]      =       [dl_manager.iter_files(a) for file in files]
              return [datasets.SplitGenerator(name=datasets.Split.TRAIN						,   gen_kwargs={'files': files})]
         lowercase__    :   int      =       []
         for split_name, files in data_files.items():
              if isinstance(a						,   a):
                   lowercase__    :   Optional[int]      =       [files]
              lowercase__    :   Tuple      =       [dl_manager.iter_files(a) for file in files]
              splits.append(datasets.SplitGenerator(name=a						,   gen_kwargs={'files': files}))
         return splits





    def       snake_case_				(      self						,   a):
         if self.config.features is not None:
              lowercase__    :   Optional[int]      =       self.config.features.arrow_schema
              if all(not require_storage_cast(a) for feature in self.config.features.values()):
                   # cheaper cast
                   lowercase__    :   Dict      =       pa.Table.from_arrays([pa_table[field.name] for field in schema]						,   schema=a)
              else:
                   # more expensive cast; allows str <-> int/float or str to Audio for example
                   lowercase__    :   Optional[Any]      =       table_cast(a						,   a)
         return pa_table





    def       snake_case_				(      self						,   a):
         lowercase__    :   List[Any]      =       self.config.features.arrow_schema if self.config.features else None
         # dtype allows reading an int column as str
         lowercase__    :   Optional[int]      =       (
             {
                 name: dtype.to_pandas_dtype() if not require_storage_cast(a) else object
                 for name, dtype, feature in zip(schema.names						,   schema.types						,   self.config.features.values())
             }
             if schema is not None
             else None
         )
         for file_idx, file in enumerate(itertools.chain.from_iterable(a)):
              lowercase__    :   int      =       pd.read_csv(a						,   iterator=a						,   dtype=a						,   **self.config.pd_read_csv_kwargs)
              try:
                   for batch_idx, df in enumerate(a):
                        lowercase__    :   List[str]      =       pa.Table.from_pandas(a)
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                        yield (file_idx, batch_idx), self._cast_table(a)
              except ValueError as e:
                   logger.error(f"""Failed to read file '{file}' with error {type(a)}: {e}""")
                   raise

