


"""simple docstring"""
import unittest

from transformers import DebertaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch

			from transformers import (
			    DebertaForMaskedLM,
			    DebertaForQuestionAnswering,
			    DebertaForSequenceClassification,
			    DebertaForTokenClassification,
			    DebertaModel,
			)
			from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST



class 			_UpperCAmelCase (							__snake_case				):






		'''simple docstring'''

		def __init__(self				,       a_				,       a_=13				,       a_=7				,       a_=True				,       a_=True				,       a_=True				,       a_=True				,       a_=99				,       a_=32				,       a_=5				,       a_=4				,       a_=37				,       a_="gelu"				,       a_=0.1				,       a_=0.1				,       a_=5_12				,       a_=16				,       a_=2				,       a_=0.02				,       a_=False				,       a_=True				,       a_="None"				,       a_=3				,       a_=4				,       a_=None				,       ):





			'''simple docstring'''

			__snake_case	:						List[Any]						=				parent
			__snake_case	:						Tuple						=				batch_size
			__snake_case	:						Union[str, Any]						=				seq_length
			__snake_case	:						List[Any]						=				is_training
			__snake_case	:						Optional[int]						=				use_input_mask
			__snake_case	:						List[Any]						=				use_token_type_ids
			__snake_case	:						Optional[int]						=				use_labels
			__snake_case	:						str						=				vocab_size
			__snake_case	:						int						=				hidden_size
			__snake_case	:						List[Any]						=				num_hidden_layers
			__snake_case	:						Optional[int]						=				num_attention_heads
			__snake_case	:						Optional[int]						=				intermediate_size
			__snake_case	:						Optional[int]						=				hidden_act
			__snake_case	:						Tuple						=				hidden_dropout_prob
			__snake_case	:						Tuple						=				attention_probs_dropout_prob
			__snake_case	:						Optional[int]						=				max_position_embeddings
			__snake_case	:						str						=				type_vocab_size
			__snake_case	:						List[str]						=				type_sequence_label_size
			__snake_case	:						Optional[int]						=				initializer_range
			__snake_case	:						Any						=				num_labels
			__snake_case	:						Dict						=				num_choices
			__snake_case	:						Any						=				relative_attention
			__snake_case	:						List[str]						=				position_biased_input
			__snake_case	:						Dict						=				pos_att_type
			__snake_case	:						List[str]						=				scope



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Union[str, Any]						=				ids_tensor([self.batch_size, self.seq_length]				,       self.vocab_size					)

			__snake_case	:						Union[str, Any]						=				None
			if self.use_input_mask:
				__snake_case	:						Dict						=				ids_tensor([self.batch_size, self.seq_length]				,       vocab_size=2					)

			__snake_case	:						Optional[int]						=				None
			if self.use_token_type_ids:
				__snake_case	:						List[Any]						=				ids_tensor([self.batch_size, self.seq_length]				,       self.type_vocab_size					)

			__snake_case	:						str						=				None
			__snake_case	:						Optional[Any]						=				None
			__snake_case	:						Optional[Any]						=				None
			if self.use_labels:
				__snake_case	:						Union[str, Any]						=				ids_tensor([self.batch_size]				,       self.type_sequence_label_size					)
				__snake_case	:						Any						=				ids_tensor([self.batch_size, self.seq_length]				,       self.num_labels					)
				__snake_case	:						Any						=				ids_tensor([self.batch_size]				,       self.num_choices					)

			__snake_case	:						Any						=				self.get_config()

			return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			return DebertaConfig(
			    vocab_size=self.vocab_size				,       hidden_size=self.hidden_size				,       num_hidden_layers=self.num_hidden_layers				,       num_attention_heads=self.num_attention_heads				,       intermediate_size=self.intermediate_size				,       hidden_act=self.hidden_act				,       hidden_dropout_prob=self.hidden_dropout_prob				,       attention_probs_dropout_prob=self.attention_probs_dropout_prob				,       max_position_embeddings=self.max_position_embeddings				,       type_vocab_size=self.type_vocab_size				,       initializer_range=self.initializer_range				,       relative_attention=self.relative_attention				,       position_biased_input=self.position_biased_input				,       pos_att_type=self.pos_att_type				,       )



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Tuple						=				self.get_config()
			__snake_case	:						Optional[int]						=				3_00
			return config



		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''simple docstring'''

			self.parent.assertListEqual(list(result.loss.size()					)				,       []					)



		def 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_				,       a_				,       a_				,       a_				,       a_				,       a_					):





			'''simple docstring'''

			__snake_case	:						int						=				DebertaModel(config=a_					)
			model.to(a_					)
			model.eval()
			__snake_case	:						str						=				model(a_				,       attention_mask=a_				,       token_type_ids=a_					)[0]
			__snake_case	:						Optional[int]						=				model(a_				,       token_type_ids=a_					)[0]
			__snake_case	:						Optional[Any]						=				model(a_					)[0]

			self.parent.assertListEqual(list(sequence_output.size()					)				,       [self.batch_size, self.seq_length, self.hidden_size]					)



		def 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_				,       a_				,       a_				,       a_				,       a_				,       a_					):





			'''simple docstring'''

			__snake_case	:						Optional[Any]						=				DebertaForMaskedLM(config=a_					)
			model.to(a_					)
			model.eval()
			__snake_case	:						int						=				model(a_				,       attention_mask=a_				,       token_type_ids=a_				,       labels=a_					)

			self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.seq_length, self.vocab_size)					)



		def 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_				,       a_				,       a_				,       a_				,       a_				,       a_					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				self.num_labels
			__snake_case	:						str						=				DebertaForSequenceClassification(a_					)
			model.to(a_					)
			model.eval()
			__snake_case	:						Dict						=				model(a_				,       attention_mask=a_				,       token_type_ids=a_				,       labels=a_					)
			self.parent.assertListEqual(list(result.logits.size()					)				,       [self.batch_size, self.num_labels]					)
			self.check_loss_output(a_					)



		def 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_				,       a_				,       a_				,       a_				,       a_				,       a_					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				self.num_labels
			__snake_case	:						Dict						=				DebertaForTokenClassification(config=a_					)
			model.to(a_					)
			model.eval()
			__snake_case	:						List[str]						=				model(a_				,       attention_mask=a_				,       token_type_ids=a_				,       labels=a_					)
			self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.seq_length, self.num_labels)					)



		def 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_				,       a_				,       a_				,       a_				,       a_				,       a_					):





			'''simple docstring'''

			__snake_case	:						Tuple						=				DebertaForQuestionAnswering(config=a_					)
			model.to(a_					)
			model.eval()
			__snake_case	:						int						=				model(
			    a_				,       attention_mask=a_				,       token_type_ids=a_				,       start_positions=a_				,       end_positions=a_				,       )
			self.parent.assertEqual(result.start_logits.shape				,       (self.batch_size, self.seq_length)					)
			self.parent.assertEqual(result.end_logits.shape				,       (self.batch_size, self.seq_length)					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				self.prepare_config_and_inputs()
			(
			    (
			    __snake_case
			)	,							(
			    __snake_case
			)	,							(
			    __snake_case
			)	,							(
			    __snake_case
			)	,							(
			    __snake_case
			)	,							(
			    __snake_case
			)	,							(
			    __snake_case
			)	,							
			)	:						List[str]						=				config_and_inputs
			__snake_case	:						str						=				{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
			return config, inputs_dict



@require_torch
class 			_UpperCAmelCase (							__snake_case,				__snake_case,				unittest.TestCase				):






		'''simple docstring'''

		lowerCamelCase__				=(
		    (
		        DebertaModel,
		        DebertaForMaskedLM,
		        DebertaForSequenceClassification,
		        DebertaForTokenClassification,
		        DebertaForQuestionAnswering,
		    )
		    if is_torch_available()
		    else ()
		)
		lowerCamelCase__				=(
		    {
		        'feature-extraction': DebertaModel,
		        'fill-mask': DebertaForMaskedLM,
		        'question-answering': DebertaForQuestionAnswering,
		        'text-classification': DebertaForSequenceClassification,
		        'token-classification': DebertaForTokenClassification,
		        'zero-shot': DebertaForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)

		lowerCamelCase__				=True
		lowerCamelCase__				=False
		lowerCamelCase__				=False
		lowerCamelCase__				=False
		lowerCamelCase__				=False



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Dict						=				DebertaModelTester(self					)
			__snake_case	:						Optional[Any]						=				ConfigTester(self				,       config_class=a_				,       hidden_size=37					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			self.config_tester.run_common_tests()



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_deberta_model(*a_					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						List[str]						=				self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_deberta_for_sequence_classification(*a_					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[Any]						=				self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_deberta_for_masked_lm(*a_					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Tuple						=				self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_deberta_for_question_answering(*a_					)



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Tuple						=				self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_deberta_for_token_classification(*a_					)



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				__snake_case	:						Optional[int]						=				DebertaModel.from_pretrained(a_					)
				self.assertIsNotNone(a_					)



@require_torch
@require_sentencepiece
@require_tokenizers
class 			_UpperCAmelCase (							unittest.TestCase				):






		'''simple docstring'''

		@unittest.skip(reason='''Model not available yet'''					)
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			pass



		@slow
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Tuple						=				DebertaModel.from_pretrained('''microsoft/deberta-base'''					)

			__snake_case	:						Optional[int]						=				torch.tensor([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]]					)
			__snake_case	:						List[Any]						=				torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]					)
			with torch.no_grad():
				__snake_case	:						List[str]						=				model(a_				,       attention_mask=a_					)[0]
			# compare the actual values for a slice.
			__snake_case	:						Union[str, Any]						=				torch.tensor(
			    [[[-0.5986, -0.8055, -0.8462], [1.4484, -0.9348, -0.8059], [0.3123, 0.0032, -1.4131]]]					)
			self.assertTrue(torch.allclose(output[:, 1:4, 1:4]				,       a_				,       atol=1E-4					)				,       f"""{output[:, 1:4, 1:4]}"""					)








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

